The pathlib module, introduced in Python 3.4 (PEP 428 — The pathlib module — object-oriented filesystem paths), makes the path-related experience much much better.
pwd
/home/skovorodkin/stack
tree
.
└── scripts
├── 1.py
└── 2.py
In order to get the current working directory, use Path.cwd():
from pathlib import Path
print(Path.cwd()) # /home/skovorodkin/stack
To get an absolute path to your script file, use the Path.resolve() method:
print(Path(__file__).resolve()) # /home/skovorodkin/stack/scripts/1.py
And to get the path of a directory where your script is located, access .parent (it is recommended to call .resolve() before .parent):
print(Path(__file__).resolve().parent) # /home/skovorodkin/stack/scripts
Remember that __file__ is not reliable in some situations: How do I get the path of the current executed file in Python?.
Please note, that Path.cwd(), Path.resolve() and other Path methods return path objects (PosixPath in my case), not strings. In Python 3.4 and 3.5 that caused some pain, because open built-in function could only work with string or bytes objects, and did not support Path objects, so you had to convert Path objects to strings or use the Path.open() method, but the latter option required you to change old code:
File scripts/2.py
from pathlib import Path
p = Path(__file__).resolve()
with p.open() as f: pass
with open(str(p)) as f: pass
with open(p) as f: pass
print('OK')
Output
python3.5 scripts/2.py
Traceback (most recent call last):
File "scripts/2.py", line 11, in <module>
with open(p) as f:
TypeError: invalid file: PosixPath('/home/skovorodkin/stack/scripts/2.py')
As you can see, open(p) does not work with Python 3.5.
PEP 519 — Adding a file system path protocol, implemented in Python 3.6, adds support of PathLike objects to the open function, so now you can pass Path objects to the open function directly:
python3.6 scripts/2.py
OK
How do I get the current file’s directory path?
I tried:
>>> os.path.abspath(__file__)
'C:\python27\test.py'
But I want:
'C:\python27\'
Mateen Ulhaq
23.8k18 gold badges95 silver badges132 bronze badges
asked Aug 7, 2010 at 12:17
4
The special variable __file__ contains the path to the current file. From that we can get the directory using either pathlib or the os.path module.
Python 3
For the directory of the script being run:
import pathlib
pathlib.Path(__file__).parent.resolve()
For the current working directory:
import pathlib
pathlib.Path().resolve()
Python 2 and 3
For the directory of the script being run:
import os
os.path.dirname(os.path.abspath(__file__))
If you mean the current working directory:
import os
os.path.abspath(os.getcwd())
Note that before and after file is two underscores, not just one.
Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of «current file». The above answer assumes the most common scenario of running a python script that is in a file.
References
- pathlib in the python documentation.
- os.path — Python 2.7, os.path — Python 3
- os.getcwd — Python 2.7, os.getcwd — Python 3
- what does the __file__ variable mean/do?
Mateen Ulhaq
23.8k18 gold badges95 silver badges132 bronze badges
answered Aug 7, 2010 at 12:24
Bryan OakleyBryan Oakley
366k52 gold badges532 silver badges679 bronze badges
30
Using Path from pathlib is the recommended way since Python 3:
from pathlib import Path
print("File Path:", Path(__file__).absolute())
print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__
Note: If using Jupyter Notebook, __file__ doesn’t return expected value, so Path().absolute() has to be used.
Mateen Ulhaq
23.8k18 gold badges95 silver badges132 bronze badges
answered Apr 30, 2018 at 10:51
Ron KalianRon Kalian
3,2422 gold badges15 silver badges23 bronze badges
10
In Python 3.x I do:
from pathlib import Path
path = Path(__file__).parent.absolute()
Explanation:
Path(__file__)is the path to the current file..parentgives you the directory the file is in..absolute()gives you the full absolute path to it.
Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path).
answered Feb 26, 2019 at 18:36
ArminiusArminius
2,2481 gold badge18 silver badges21 bronze badges
2
Try this:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
answered May 23, 2019 at 9:51
1
import os
print(os.path.dirname(__file__))
JayRizzo
3,1053 gold badges33 silver badges46 bronze badges
answered Aug 7, 2010 at 12:24
chefsmartchefsmart
6,8339 gold badges42 silver badges47 bronze badges
3
I found the following commands return the full path of the parent directory of a Python 3 script.
Python 3 Script:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pathlib import Path
#Get the absolute path of a Python3.6 and above script.
dir1 = Path().resolve() #Make the path absolute, resolving any symlinks.
dir2 = Path().absolute() #See @RonKalian answer
dir3 = Path(__file__).parent.absolute() #See @Arminius answer
dir4 = Path(__file__).parent
print(f'dir1={dir1}ndir2={dir2}ndir3={dir3}ndir4={dir4}')
REMARKS !!!!
dir1anddir2works only when running a script located in the current working directory, but will break in any other case.- Given that
Path(__file__).is_absolute()isTrue, the use of the.absolute()method in dir3 appears redundant. - The shortest command that works is dir4.
Explanation links: .resolve(), .absolute(), Path(file).parent().absolute()
answered Oct 12, 2019 at 18:20
Sun BearSun Bear
7,43611 gold badges53 silver badges98 bronze badges
2
USEFUL PATH PROPERTIES IN PYTHON:
from pathlib import Path
#Returns the path of the current directory
mypath = Path().absolute()
print('Absolute path : {}'.format(mypath))
#if you want to go to any other file inside the subdirectories of the directory path got from above method
filePath = mypath/'data'/'fuel_econ.csv'
print('File path : {}'.format(filePath))
#To check if file present in that directory or Not
isfileExist = filePath.exists()
print('isfileExist : {}'.format(isfileExist))
#To check if the path is a directory or a File
isadirectory = filePath.is_dir()
print('isadirectory : {}'.format(isadirectory))
#To get the extension of the file
fileExtension = mypath/'data'/'fuel_econ.csv'
print('File extension : {}'.format(filePath.suffix))
OUTPUT:
ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED
Absolute path : D:StudyMachine LearningJupitor NotebookJupytorNotebookTest2Udacity_ScriptsMatplotlib and seaborn Part2
File path : D:StudyMachine LearningJupitor NotebookJupytorNotebookTest2Udacity_ScriptsMatplotlib and seaborn Part2datafuel_econ.csv
isfileExist : True
isadirectory : False
File extension : .csv
answered Mar 10, 2019 at 4:06
Arpan SainiArpan Saini
4,4891 gold badge39 silver badges50 bronze badges
3
works also if __file__ is not available (jupyter notebooks)
import sys
from pathlib import Path
path_file = Path(sys.path[0])
print(path_file)
Also uses pathlib, which is the object oriented way of handling paths in python 3.
answered Jan 18 at 10:37
Markus DutschkeMarkus Dutschke
9,0534 gold badges58 silver badges56 bronze badges
Python 2 and 3
You can simply also do:
from os import sep
print(__file__.rsplit(sep, 1)[0] + sep)
Which outputs something like:
C:my_foldersub_folder
answered Aug 25, 2022 at 19:06
Giorgos XouGiorgos Xou
1,3011 gold badge12 silver badges32 bronze badges
1
IPython has a magic command %pwd to get the present working directory. It can be used in following way:
from IPython.terminal.embed import InteractiveShellEmbed
ip_shell = InteractiveShellEmbed()
present_working_directory = ip_shell.magic("%pwd")
On IPython Jupyter Notebook %pwd can be used directly as following:
present_working_directory = %pwd
answered Mar 7, 2018 at 5:50
Nafeez QuraishiNafeez Quraishi
5,2302 gold badges27 silver badges34 bronze badges
8
I have made a function to use when running python under IIS in CGI in order to get the current folder:
import os
def getLocalFolder():
path=str(os.path.dirname(os.path.abspath(__file__))).split(os.sep)
return path[len(path)-1]
MisterMiyagi
43k10 gold badges96 silver badges112 bronze badges
answered Dec 27, 2018 at 10:35
Gil AllenGil Allen
1,15914 silver badges23 bronze badges
This can be done without a module.
def get_path():
return (__file__.replace(f"<your script name>.py", ""))
print(get_path())
answered Dec 27, 2022 at 19:14
In this article, we will cover How to Get and Change the Current Working Directory in Python. While working with file handling you might have noticed that files are referenced only by their names, e.g. ‘GFG.txt’ and if the file is not located in the directory of the script, Python raises an error.
The concept of the Current Working Directory (CWD) becomes important here. Consider the CWD as the folder, the Python is operating inside. Whenever the files are called only by their name, Python assumes that it starts in the CWD which means that a name-only reference will be successful only if the file is in the Python’s CWD.
Note: The folder where the Python script is running is known as the Current Directory. This may not be the path where the Python script is located.
What is the Python os module?
Python provides os module for interacting with the operating system. This module comes under Python’s standard utility module. All functions in the os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.
Using os.getcwd() method to get Python Script location
The os.getcwd() method is used for getting the Current Working Directory in Python. The absolute path to the current working directory is returned in a string by this function of the Python OS module.
Syntax of os.getcwd() method
Syntax: os.getcwd()
Parameter: No parameter is required.
Return Value: This method returns a string which represents the current working directory.
Example 1: Get the current working directory using os.getcwd()
I have placed the Python file (test.py) inside /home/tuhingfg/Documents/Scripts/test.py. And running the Python Script from the Scripts folder.
Python3
import os
print("File location using os.getcwd():", os.getcwd())
Output:
File location using os.getcwd(): /home/tuhingfg/Documents/Scripts
Note: Using os.getcwd() doesn’t work as expected when running the Python code from different directory as the Python script.
Example 2: Unexpected result when running Python script from different directory other than script using os.getcwd()
Python3
import os
print("File location using os.getcwd():", os.getcwd())
Output:
Get Script location using os.getcwd()
Explanation: The Python script is placed inside /home/tuhingfg/Documents/Scripts. When we run the script from inside the same folder, it gives correct script location. But when we change our directory to some other place, it outputs the location of that directory. This is because, os.getcwd() considers the directory from where we are executing the script. Based on this, the result of os.getcwd() also varies.
Using os.path.realpath() method to get Python Script location
os.path.realpath() can be used to get the path of the current Python script. Actually, os.path.realpath() method in Python is used to get the canonical path of the specified filename by eliminating any symbolic links encountered in the path. A special variable __file__ is passed to the realpath() method to get the path of the Python script.
Note: __file__ is the pathname of the file from which the module was loaded if it was loaded from a file.
Syntax of os.path.realpath() method
Syntax: os.path.realpath(path)
Parameter:
- path: A path-like object representing the file system path. A path-like object is either a string or bytes object representing a path.
Return Type: This method returns a string value which represents the canonical path.
Example: Get the directory script path using __file__ special variable
Inside a Python script, we can use os.path.realpath() and __file__ special variable to get the location of the script. And the result obtained from this method doesn’t depend on the location of execution of the script.
Python3
import os
print("File location using os.getcwd():", os.getcwd())
print(f"File location using __file__ variable: {os.path.realpath(os.path.dirname(__file__))}")
Output:
Explanation: Here, the os.getcwd() and __file__ provides two different results. Since, we are executing the script from a different folder than the script, os.getcwd() output has changed according to the folder of execution of the script. But __file__ generates the constant result irrespective of the current working directory.
Last Updated :
09 Sep, 2022
Like Article
Save Article
Python становится все популярнее благодаря относительной простоте изучения, универсальности и другим преимуществам. Правда, у начинающих разработчиков нередко возникают проблемы при работе с файлами и файловой системой. Просто потому, что они знают не все команды, которые нужно знать.
Эта статья предназначена как раз для начинающих разработчиков. В ней описаны 8 крайне важных команд для работы с файлами, папками и файловой системой в целом. Все примеры из этой статьи размещены в Google Colab Notebook (ссылка на ресурс — в конце статьи).
Показать текущий каталог
Самая простая и вместе с тем одна из самых важных команд для Python-разработчика. Она нужна потому, что чаще всего разработчики имеют дело с относительными путями. Но в некоторых случаях важно знать, где мы находимся.
Относительный путь хорош тем, что работает для всех пользователей, с любыми системами, количеством дисков и так далее.
Так вот, для того чтобы показать текущий каталог, нужна встроенная в Python OS-библиотека:
import os
os.getcwd()
Ее легко запомнить, так что лучше выучить один раз, чем постоянно гуглить. Это здорово экономит время.
Имейте в виду, что я использую Google Colab, так что путь /content является абсолютным.
Проверяем, существует файл или каталог
Прежде чем задействовать команду по созданию файла или каталога, стоит убедиться, что аналогичных элементов нет. Это поможет избежать ряда ошибок при работе приложения, включая перезапись существующих элементов с данными.
Функция os.path.exists () принимает аргумент строкового типа, который может быть либо именем каталога, либо файлом.
В случае с Google Colab при каждом запуске создается папка sample_data. Давайте проверим, существует ли такой каталог. Для этого подойдет следующий код:
os.path.exists('sample_data')
Эта же команда подходит и для работы с файлами:
os.path.exists(‘sample_data/README.md’)
Если папки или файла нет, команда возвращает false.
Объединение компонентов пути
В предыдущем примере я намеренно использовал слеш «/» для разделителя компонентов пути. В принципе это нормально, но не рекомендуется. Если вы хотите, чтобы ваше приложение было кроссплатформенным, такой вариант не подходит. Так, некоторые старые версии ОС Windows распознают только слеш «» в качестве разделителя.
Но не переживайте, Python прекрасно решает эту проблему благодаря функции os.path.join (). Давайте перепишем вариант из примера в предыдущем пункте, используя эту функцию:
os.path.exists(os.path.join('sample_data', 'README.md'))
Создание директории
Ну а теперь самое время создать директорию с именем test_dir внутри рабочей директории. Для этого можно использовать функцию
os.mkdir():
os.mkdir('test_dir')
Давайте посмотрим, как это работает на практике.
Если же мы попытаемся создать каталог, который уже существует, то получим исключение.
Именно поэтому рекомендуется всегда проверять наличие каталога с определенным названием перед созданием нового:
if not os.path.exists('test_dir'):
os.mkdir('test_dir')
Еще один совет по созданию каталогов. Иногда нам нужно создать подкаталоги с уровнем вложенности 2 или более. Если мы все еще используем os.mkdir (), нам нужно будет сделать это несколько раз. В этом случае мы можем использовать os.makedirs (). Эта функция создаст все промежуточные каталоги так же, как флаг mkdir -p в системе Linux:
os.makedirs(os.path.join('test_dir', 'level_1', 'level_2', 'level_3'))
Вот что получается в результате.
Показываем содержимое директории
Еще одна полезная команда — os.listdir(). Она показывает все содержимое каталога.
Команда отличается от os.walk (), где последний рекурсивно показывает все, что находится «под» каталогом. os.listdir () намного проще в использовании, потому что просто возвращает список содержимого:
os.listdir('sample_data')
В некоторых случаях нужно что-то более продвинутое — например, поиск всех CSV-файлов в каталоге «sample_data». В этом случае самый простой способ — использовать встроенную библиотеку glob:
from glob import globlist(glob(os.path.join('sample_data', '*.csv')))
Перемещение файлов
Самое время попробовать переместить файлы из одной папки в другую. Рекомендованный способ — еще одна встроенная библиотека shutil.
Сейчас попробуем переместить все CSV-файлы из директории «sample_data» в директорию «test_dir». Ниже — пример кода для выполнения этой операции:
import shutilfor file in list(glob(os.path.join('sample_data', '*.csv'))):
shutil.move(file, 'test_dir')
Кстати, есть два способа выполнить задуманное. Например, мы можем использовать библиотеку OS, если не хочется импортировать дополнительные библиотеки. Как os.rename, так и os.replace подходят для решения задачи.
Но обе они недостаточно «умные», чтобы позволить перемесить файлы в каталог.
Чтобы все это работало, нужно явно указать имя файла в месте назначения. Ниже — код, который это позволяет сделать:
for file in list(glob(os.path.join('test_dir', '*.csv'))):
os.rename(
file,
os.path.join(
'sample_data',
os.path.basename(file)
))
Здесь функция os.path.basename () предназначена для извлечения имени файла из пути с любым количеством компонентов.
Другая функция, os.replace (), делает то же самое. Но разница в том, что os.replace () не зависит от платформы, тогда как os.rename () будет работать только в системе Unix / Linux.
Еще один минус — в том, что обе функции не поддерживают перемещение файлов из разных файловых систем, в отличие от shutil.
Поэтому я рекомендую использовать shutil.move () для перемещения файлов.
Копирование файлов
Аналогичным образом shutil подходит и для копирования файлов по уже упомянутым причинам.
Если нужно скопировать файл README.md из папки «sample_data» в папку «test_dir», поможет функция shutil.copy():
shutil.copy(
os.path.join('sample_data', 'README.md'),
os.path.join('test_dir')
)
Удаление файлов и папок
Теперь пришел черед разобраться с процедурой удаления файлов и папок. Нам здесь снова поможет библиотека OS.
Когда нужно удалить файл, нужно воспользоваться командой os.remove():
os.remove(os.path.join('test_dir', 'README(1).md'))
Если требуется удалить каталог, на помощь приходит os.rmdir():
os.rmdir(os.path.join('test_dir', 'level_1', 'level_2', 'level_3'))
Однако он может удалить только пустой каталог. На приведенном выше скриншоте видим, что удалить можно лишь каталог level_3. Что если мы хотим рекурсивно удалить каталог level_1? В этом случае зовем на помощь shutil.
Функция shutil.rmtree() сделает все, что нужно:
shutil.rmtree(os.path.join('test_dir', 'level_1'))
Пользоваться ею нужно с осторожностью, поскольку она безвозвратно удаляет все содержимое каталога.
Собственно, на этом все. 8 важных операций по работе с файлами и каталогами в среде Python мы знаем. Что касается ссылки, о которой говорилось в анонсе, то вот она — это Google Colab Network с содержимым, готовым к запуску.
Модуль Python OS используется для работы с операционной системой и является достаточно большим, что бы более конкретно описать его применение. С помощью его мы можем получать переменные окружения PATH, названия операционных систем, менять права на файлах и многое другое. В этой статье речь пойдет про работу с папками и путями, их создание, получение списка файлов и проверка на существование. Примеры приведены с Python 3, но и с предыдущими версиями ошибок быть не должно.
Модуль OS не нуждается в дополнительной установке, так как поставляется вместе с инсталлятором Python.
Получение директорий и списка файлов
Есть несколько способов вернуть список каталогов и файлов по указанному пути. Первый способ используя os.walk, который возвращает генератор:
import os
path = 'C:/windows/system32/drivers/'
print(path)
Такие объекты можно итерировать для понятного отображения структуры:
import os
path = 'C:/Folder1'
for el in os.walk(path):
print(el)
Сам кортеж делится на 3 объекта: текущая директория, имя вложенных папок (если есть), список файлов. Я так же разделил их на примере ниже:
import os
path = 'C:/Folder1'
for dirs,folder,files in os.walk(path):
print('Выбранный каталог: ', dirs)
print('Вложенные папки: ', folder)
print('Файлы в папке: ', files)
print('n')
Os.walk является рекурсивным методом. Это значит, что для поиска файлов в конкретной директории вы будете итерировать и все вложенные папки. Обойти это с помощью самого метода нельзя, но вы можете использовать break так как os.walk возвращает указанную директорию первой. Можно так же использовать next():
import os
path = 'C:/Folder1'
for dirs,folder,files in os.walk(path):
print('Выбранный каталог: ', dirs)
print('Вложенные папки: ', folder)
print('Файлы в папке: ', files)
print('n')
# Отобразит только корневую папку и остановит цикл
break
# Отобразит первый итерируемый объект
directory = os.walk(path)
print(next(directory))
Получение файлов через listdir
Есть еще один метод получения файлов используя listdir. Отличия от предыдущего метода в том, что у нас не будет разделения файлов и папок. Он так же не является рекурсивным:
import os
path = 'C:/Folder1'
directory = os.listdir(path)
print(directory)
Получение полного абсолютного пути к файлам
Для последующего чтения файла нам может понадобится абсолютный путь. Мы можем использовать обычный метод сложения строк или метод os.path.join, который сделает то же самое, но и снизит вероятность ошибки если программа работает на разных ОС:
import os
path = 'C:/Folder1'
for dirs,folder,files in os.walk(path):
print('Выбранный каталог: ', dirs)
print('Вложенные папки: ', folder)
print('Файлы в папке: ', files)
print('Полный путь к файлу: ', os.path.join(dirs, files))
Исключение каталогов или файлов из списка
У нас может быть список полных путей, например из списка выше, из которого мы хотим исключить папки или файлы. Для этого используется os.path.isfile:
import os
path = ['C:/Folder1',
'C:/Folder1/Folder2/file2.txt']
for el in path:
if os.path.isfile(el):
print('Это файл: ', el)
else:
print('Это папка: ', el)
Такой же принцип имеют следующие методы:
- os.path.isdir() — относится ли путь к папке;
- os.path.islink() — относится ли путь к ссылке;
Получение расширения файлов
Расширение файла можно получить с помощью os.path.splittext(). Этот метод вернет путь до расширения и само расширение. Этот метод исключает ситуацию, когда точка может стоять в самом пути. Если в качестве пути мы выберем каталог (который не имеет расширения) , результатом будет пустая строка:
import os
path = ['C:/Folder1',
'C:/Folder1/Folder2/file2.txt']
for el in path:
print(os.path.splitext(el))
os.path.basename(path) — вернет имя файла и расширение.
Создание и удаление директорий
Методы по изменению папок следующие:
- os.mkdir() — создаст папку;
- os.rename() — переименует;
- os.rmdir() — удалит.
import os
# Имя новой папки
path = 'C:/Folder1/NewFolder'
# Ее создание
os.mkdir(path)
# Переименуем папку
os.rename(path, 'C:/Folder1/NewFolder2')
# Удалим
os.rmdir('C:/Folder1/NewFolder2')
Если попытаться создать несколько вложенных папок сразу, используя предыдущий пример, появится ошибка FileNotFoundError. Создание папок включая промежуточные выполняется с os.makedirs():
import os
path = 'C:/Folder1/Folder1/Folder1/'
os.makedirs(path)
Проверка директорий и файлов на существование
Если мы пытаемся создать папку с существующим именем, то получим ошибку FileExistsError. Один из способов этого избежать — использование os.path.exists(), который вернет True в случае существования файла или папки:
import os
path = ['C:/Folder1/file1.txt',
'C:/Folder1/NotExistFolder']
for el in path:
if os.path.exists(el):
print('Такой путь существует: ', el)
else:
print('Такого пути нет', el)
Получение и изменение текущей директории
Запуская любую программу или консоль, например CMD, мы это делаем из определенной директории. С этой и соседней директорией мы можем работать без указания полного пути. Для того что бы узнать такую директорию в Python используется метод os.getcwd():
import os
current_dir = os.getcwd()
print(current_dir)
В директории ‘D:’ сохранен мой файл, с которого я запускаю методы. Вы можете изменить такую директорию с os.chdir() . Такой подход удобен, когда файлы, с которыми вы работаете в основном находятся в другом месте и вы сможете избежать написания полного пути:
import os
current_dir = os.getcwd()
print(current_dir)
new_dir = os.chdir('D:/newfolder/')
print(os.getcwd())
Так же как и в любых языках, в любых методах описанных выше, вы можете использовать ‘..’ для работы с директорией выше или ‘/’ для работы со внутренней:
import os
# Текущая директория
print(os.getcwd())
# Переход во внутреннюю
old_dir = os.chdir('/newfolder/')
print(os.getcwd())
# Переход на уровень выше
new_dir = os.chdir('..')
print(os.getcwd())

…
Теги:
#python
#os

































