How to Check if a File Exists in Python with isFile() and exists()

Dionysia Lemonaki

When working with files in Python, there may be times when you need to check whether a file exists or not.
But why should you check if a file exists in the first place?
Confirming the existence of a specific file comes in handy when you want to perform particular operations, such as opening, reading from, or writing to that file.
If you attempt to perform any of the operations mentioned above and the file doesn’t exist, you will come across bugs and your program will end up crashing.
So, to perform operations and prevent your program from crashing, it is a helpful first step to check if a file exists on a given path.
Thankfully, Python has multiple built-in ways of checking whether a file exists, like the built-in os.path and pathlib modules.
Specifically, when using the os.path module, you have access to:
- the os.path.isfile(path) method that returns True if the path is a file or a symlink to a file.
- the os.path.exists(path) method that returns True if the path is a file, directory, or a symlink to a file.
And when using the pathlib module, you have access to the pathlib.Path(path).is_file() function, which returns True if path is a file and it exists.
In this article, you will learn how to use Python to check if a file exists using the os.path and pathlib modules.
How to Check if a File Exists Using the os.path Module
The os module is part of the standard library (also known as stdlib ) in Python and provides a way of accessing and interacting with the operating system.
With the os module, you can use functionalities that depend on the underlying operating system, such as creating and deleting files and folders, as well as copying and moving contents of folders, to name a few.
Since it is part of the standard library, the os module comes pre-packaged when you install Python on your local system. You only need to import it at the top of your Python file using the import statement:
The os.path is a submodule of the os module.
It provides two methods for manipulating files — specifically the isfile() and exists() methods that output either True or False , depending on whether a file exists or not.
Since you will be using the os.path submodule, you will instead need to import that at the top of your file, like so:
How to Check if a File Exists Using the os.path.isfile() Method in Python
The general syntax for the isfile() method looks like this:
The method accepts only one argument, path , which represents the defined path to the file whose existence you want to confirm.
The path argument is a string enclosed in quotation marks.
The return value of the isfile() method is either a Boolean value — either True or False depending on whether that file exists.
Keep in mind that if the path ends in a directory name and not a file, it will return False .
Let’s see an example of the method in action.
I want to check whether an example.txt file exists in my current working directory, python_project .
The example.txt is on the same level as my Python file main.py , so I am using a relative file path.
I store the path to example.txt in a variable named path .
Then I use the isfile() method and pass path as an argument to check whether example.txt exists in that path.
Since the file does exist, the return value is True :
Ok, but what about absolute paths?
Here is the equivalent code when using an absolute path. The example.txt file is inside a python_project directory, which is inside my home directory, /Users/dionysialemonaki/ :
And as mentioned earlier, the isfile() method only works for files and not directories:
If your path ends in a directory, the return value is False .
How to Check if a File Exists Using the os.path.exists() Method in Python
The general syntax for the exists() method looks like this:
As you can see from the syntax above, the exists() method looks similar to the isfile() method.
The os.path.exists() method checks to see whether the specified path exists.
The main difference between exists() and isfile() is that exists() will return True if the given path to a folder or a file exists, whereas isfile() returns True only if the given path is a path to a file and not a folder.
Keep in mind that if you don’t have access and permissions to the directory, exists() will return False even if the path exists.
Let’s go back to the example from the previous section and check whether the example.txt file exists in the current working directory using the exists() method:
Since the path to example.txt exists, the output is True .
As mentioned earlier, the exists() method checks to see if the path to a directory is valid.
In the previous section, when I used the isfile() method and the path pointed to a directory, the output was False even though that directory existed.
When using the exists() method, if the path to a directory exists, the output will be True :
The exists() method comes in handy when you want to check whether a file or directory exists.
How to Check if a File Exists Using the pathlib Module
Python 3.4 version introduced the pathlib module.
Using the pathlib module to check whether a file exists or not is an object-oriented approach to working with filesystem paths.
Like the os.path module from earlier on, you need to import the pathlib module.
Specifically, you need to import the Path class from the pathlib module like so:
Then, create a new instance of the Path class and initialize it with the file path you want to check:
You can use the type() function to check the data type:
This confirms that you created a Path object.
Let’s see how to use the pathlib module to check if a file exists using the is_file() method, one of the built-in methods available with the pathlib module.
How to Check if a File Exists Using the Path.is_file() Method in Python
The is_file() method checks if a file exists.
It returns True if the Path object points to a file and False if the file doesn’t exist.
Let’s see an example of how it works:
Since the example.txt file exists in the specified path, the is_file() method returns True .
Conclusion
In this article, you learned how to check if a file exists in Python using the os.path and pathlib modules and their associated methods.
Hopefully, you have understood the differences between the modules and when to use each one.
8 команд для Python по работе с файлами и файловой системой, которые обязательно нужно знать

Python становится все популярнее благодаря относительной простоте изучения, универсальности и другим преимуществам. Правда, у начинающих разработчиков нередко возникают проблемы при работе с файлами и файловой системой. Просто потому, что они знают не все команды, которые нужно знать.
Эта статья предназначена как раз для начинающих разработчиков. В ней описаны 8 крайне важных команд для работы с файлами, папками и файловой системой в целом. Все примеры из этой статьи размещены в Google Colab Notebook (ссылка на ресурс — в конце статьи).
Показать текущий каталог
Самая простая и вместе с тем одна из самых важных команд для Python-разработчика. Она нужна потому, что чаще всего разработчики имеют дело с относительными путями. Но в некоторых случаях важно знать, где мы находимся.
Относительный путь хорош тем, что работает для всех пользователей, с любыми системами, количеством дисков и так далее.
Так вот, для того чтобы показать текущий каталог, нужна встроенная в Python OS-библиотека:
Ее легко запомнить, так что лучше выучить один раз, чем постоянно гуглить. Это здорово экономит время.

Имейте в виду, что я использую Google Colab, так что путь /content является абсолютным.
Проверяем, существует файл или каталог
Прежде чем задействовать команду по созданию файла или каталога, стоит убедиться, что аналогичных элементов нет. Это поможет избежать ряда ошибок при работе приложения, включая перезапись существующих элементов с данными.
Функция os.path.exists () принимает аргумент строкового типа, который может быть либо именем каталога, либо файлом.
В случае с Google Colab при каждом запуске создается папка sample_data. Давайте проверим, существует ли такой каталог. Для этого подойдет следующий код:

Эта же команда подходит и для работы с файлами:

Если папки или файла нет, команда возвращает false.

Объединение компонентов пути
В предыдущем примере я намеренно использовал слеш "/" для разделителя компонентов пути. В принципе это нормально, но не рекомендуется. Если вы хотите, чтобы ваше приложение было кроссплатформенным, такой вариант не подходит. Так, некоторые старые версии ОС Windows распознают только слеш "\" в качестве разделителя.
Но не переживайте, Python прекрасно решает эту проблему благодаря функции os.path.join (). Давайте перепишем вариант из примера в предыдущем пункте, используя эту функцию:
Создание директории
Ну а теперь самое время создать директорию с именем test_dir внутри рабочей директории. Для этого можно использовать функцию
os.mkdir():
Давайте посмотрим, как это работает на практике.

Если же мы попытаемся создать каталог, который уже существует, то получим исключение.

Именно поэтому рекомендуется всегда проверять наличие каталога с определенным названием перед созданием нового:
Еще один совет по созданию каталогов. Иногда нам нужно создать подкаталоги с уровнем вложенности 2 или более. Если мы все еще используем os.mkdir (), нам нужно будет сделать это несколько раз. В этом случае мы можем использовать os.makedirs (). Эта функция создаст все промежуточные каталоги так же, как флаг mkdir -p в системе Linux:
Вот что получается в результате.

Показываем содержимое директории
Еще одна полезная команда — os.listdir(). Она показывает все содержимое каталога.
Команда отличается от os.walk (), где последний рекурсивно показывает все, что находится «под» каталогом. os.listdir () намного проще в использовании, потому что просто возвращает список содержимого:

В некоторых случаях нужно что-то более продвинутое — например, поиск всех CSV-файлов в каталоге «sample_data». В этом случае самый простой способ — использовать встроенную библиотеку glob:

Перемещение файлов
Самое время попробовать переместить файлы из одной папки в другую. Рекомендованный способ — еще одна встроенная библиотека shutil.
Сейчас попробуем переместить все CSV-файлы из директории «sample_data» в директорию «test_dir». Ниже — пример кода для выполнения этой операции:

Кстати, есть два способа выполнить задуманное. Например, мы можем использовать библиотеку OS, если не хочется импортировать дополнительные библиотеки. Как os.rename, так и os.replace подходят для решения задачи.
Но обе они недостаточно «умные», чтобы позволить перемесить файлы в каталог.

Чтобы все это работало, нужно явно указать имя файла в месте назначения. Ниже — код, который это позволяет сделать:

Здесь функция os.path.basename () предназначена для извлечения имени файла из пути с любым количеством компонентов.
Другая функция, os.replace (), делает то же самое. Но разница в том, что os.replace () не зависит от платформы, тогда как os.rename () будет работать только в системе Unix / Linux.
Еще один минус — в том, что обе функции не поддерживают перемещение файлов из разных файловых систем, в отличие от shutil.
Поэтому я рекомендую использовать shutil.move () для перемещения файлов.
Копирование файлов
Аналогичным образом shutil подходит и для копирования файлов по уже упомянутым причинам.
Если нужно скопировать файл README.md из папки «sample_data» в папку «test_dir», поможет функция shutil.copy():


Удаление файлов и папок
Теперь пришел черед разобраться с процедурой удаления файлов и папок. Нам здесь снова поможет библиотека OS.
Когда нужно удалить файл, нужно воспользоваться командой os.remove():
Если требуется удалить каталог, на помощь приходит os.rmdir():

Однако он может удалить только пустой каталог. На приведенном выше скриншоте видим, что удалить можно лишь каталог level_3. Что если мы хотим рекурсивно удалить каталог level_1? В этом случае зовем на помощь shutil.

Функция shutil.rmtree() сделает все, что нужно:
Пользоваться ею нужно с осторожностью, поскольку она безвозвратно удаляет все содержимое каталога.
Собственно, на этом все. 8 важных операций по работе с файлами и каталогами в среде Python мы знаем. Что касается ссылки, о которой говорилось в анонсе, то вот она — это Google Colab Network с содержимым, готовым к запуску.
Как проверить, существует ли файл при помощи Python

Руководство для тех, кому нужно узнать, существует ли файл (или папка) при помощи встроенных возможностей и функций Python из стандартной библиотеки.
Способность проверять, существует ли файл на диске или нет — очень важно для большинства программ Python:
Возможно, вам нужно убедиться в том, что файл с данным доступен, перед тем как вы попробуете загрузить его, или вам нужно предотвратить повторную запись файла в Python. Это же подходит и для папок. Возможно, вам нужно убедиться в том, что папка доступна, перед тем как ваша программа запустится.
В Python есть несколько способов подтвердить существование папки или файла, пользуясь встроенными в ядро языка функциями и стандартной библиотекой Python.
В данном руководстве вы увидите три отдельные техники для проверки существования файла в Python, с примерами кода и характерными преимуещствами и недостатками.
Проверяем если файл существует os.path.exists() и os.path.isfile()
Самый простой способ проверки существования файла в Python — это использование методов exists() и isfile() из модуля os.path в стандартной библиотеке.
Эти функции доступны в Python 2 и Python 3.7, и обычно их рекомендуют в первую очередь, если обращаться за помощью к документации Python или гуглу за решением проблемы.
Есть вопросы по Python?
На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!
Telegram Чат & Канал
Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!
Паблик VK
Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!
Вот пример того, как работать с функцией os.path.exists() . Мы проверим несколько путей (файлы и папки) на наличие:
Как мы видим, вызов os.path.exists() возвращает True для файлов и папок. Если вы хотите убедиться, что заданный путь указывает на файл, но не на папку, вы можете использовать функцию os.path.isfile()
Для обеих функций важно помнить о том, что они проверяют только существует файл, или нет, а не наличие доступа программы к нему. Если подтверждение доступа к файлу важно, то вам нужно выполнить простое открытия файла и поймать исключение IOError.
Мы вернемся к этой технике, когда будем подводить итоги в конце руководства. Но перед этим, рассмотрим еще один способ проверки существования файла в Python.
Проверка существует ли файл используя open() и try … except
Мы только что рассматривали, как функции в модуле os.path могут быть использованы для проверки существования файла или папки.
Есть еще один прямолинейный алгоритм Python для проверки существования файла: Вы просто пытаетесь открыть файл при помощи встроенной функции open() , вот так:
Если файл существует, то файл успешно откроется и вернет валидный объект для дальнейшей обработки файла. Если файл не существует, появится ошибка FileNotFoundError:
Ошибка FileNotFoundError возникает, когда файл или папка запрошена, но не существует. Относится к errno ENOENT.
Это значит, что вы можете получить ошибку FileNotFoundError в своем коде, и использовать ее для обнаружения того, существует файл или нет. Вот пример кода, который демонстрирует работу этой техники:
Обратите внимание, мы мгновенно вызываем метод close() для объекта файла для освобождения дескриптора файла. Это считается хорошей практикой при работе с файлами в Python:
Если вы не закроете дескриптор файлов, то будет сложно понять, когда именно он будет закрыт автоматически во время работы Python. Это занимает ресурсы системы и может снизить производительность ваших программ.
Вместо того, чтобы закрывать файл при помощи метода close() , есть еще один способ, которым можно воспользоваться контекстным менеджером и оператора with для автоматического закрытия файла.
Теперь, та же техника “просто попробуем открыть файл” также работает для выяснения, является ли файл доступным и читаемым. Вместо поиска ошибок FileNotFoundError, вам нужно искать любые ошибки типа IOError:
Если вы часто используете этот шаблон, вы можете выделить его в вспомогательную функцию, которая позволит вам проверить, существует ли файл и является ли он в то же время доступным:
Как альтернатива, вы можете использовать функцию os.access() из стандартной библиотеке для проверки того, существует ли файл и является ли он доступным в то же время. Это может быть похоже на использование функции path.exists() , если файл существует.
Использование open() и try . except имеет некоторые преимущества, когда доходит до обработки файлов в Python. Это может помочь вам избежать накладок, вызванных определенными условиями существования файла:
Представим, что файл существует в тот момент, когда вы запускаете проверку, файл удаляется другим процессом независящий от вас. Когда вы пытаетесь открыть файл для работы с ним, он исчезает и ваша программа получает ошибку.
Мы рассмотрим этот случай в конце руководства. Но перед этим, запрыгнем в еще одну кроличью нору. Рассмотрим еще один способ того, как проверить, существует ли файл в Python.
Пример проверки существования файла pathlib.Path.exists() (Python 3.4+)
Python 3.4 и выше содержит модуль pathlib , который предоставляет объектно-ориентированный интерфейс для работы с путями файловых систем. Использование этого модуля намного приятнее, чем работа с путями в виде объектов строк.
Он предоставляет абстракции и вспомогательные функции для множества операций с файловыми системами, включая проверку на наличие и поиск того, указывает ли путь на файл или папку.
Чтобы узнать, указывает ли путь на настоящий файл, вы можете использовать метод Path.exists() . Чтобы узнать, является путь файлом, или символической ссылкой, а не папкой, вам захочется воспользоваться Path.is_file() .
Вот рабочий пример для обоих методов pathlib.Path :
Как мы видим, этот подход по своему принципу схож с проверкой при помощи функций из модуля os.path .
Главное отличие в том, что pathlib предоставляет более чистый объекно-ориентированный интерфейс для работы с файловой системой. Вам больше не нужно работать с объектами str, представляющими пути файлов — вместо этого, вы обрабатываете объекты Path с релевантными методами и связанными с ними атрибутами.
Использование pathlib и преимущества объектно-ориентированного интерфейса может сделать ваш код обработки более читаемым и понятным. Не будем лгать и говорить, что это панацея. Но в ряде случаев это может помочь вам написать более “лучшую” версию программы Python.
Модуль pathlib также доступен как сторонний модуль с бэкпортом для PyPl, который работает на Python 2.x и 3.х Вы можете найти его здесь: pathlib2.
Подведем итоги проверки на наличие файла в Python
В данном руководстве мы сравнили три разных метода определения наличия или отсутствия файла в Python. Один метод также позволяет нам проверить, существует ли файл и является ли он доступным в то же время.
Конечно, имея в распоряжении три способа, вы можете подумать:
Какой способ проверки наличия файла при помощи Python является предпочтительнее?
В большинстве случаев, когда вам нужно проверить наличие файла, рекомендуется использование встроенного метода pathlib.Path.exists() на Python 3.4 и выше, или функцию os.path.exists() для Python 2.
Однако, есть одна важная оговорка…
Следует помнить о том, что файл который считается существующим, после проведения проверки может исчезнуть из за других программ который с ним работают.
Хотя вероятность такого события невысока, вполне может быть так, что файл будет существовать только во время проверки, и мгновенно будет удален после.
Чтобы избежать такой ситуации, стоит опираться не только на вопрос “существует ли файл?”. Вместо этого, неплохо просто попытаться сразу выполнить желаемую операцию. Это также называется “easier to ask for forgiveness than permission” (EAFP) (проще просить прощения, чем разрешения). Такой подход часто рекомендуется при работе с Python.
Например, вместо проверки того, существует ли файл перед тем, как его открыть, вам захочется просто попробовать открыть его и готовиться ловить ошибку FileNotFoundError, которая говорит нам о том, что файл недоступен. Это позволит избежать состояния гонки.
Итак, если вы планируете работать с файлом сразу после проверки, например, прочитать его содержимое путем внесение новых данных в него, рекомендуется выполнить проверку на наличие при помощи метода open() с последующей обработкой ошибки, пользуясь подходом EAFP. Это позволит вам избежать состояния гонки в вашем коде обработки файлов Python.

Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.
os.path — Common pathname manipulations¶
Source code: Lib/posixpath.py (for POSIX) and Lib/ntpath.py (for Windows).
This module implements some useful functions on pathnames. To read or write files see open() , and for accessing the filesystem see the os module. The path parameters can be passed as strings, or bytes, or any object implementing the os.PathLike protocol.
Unlike a Unix shell, Python does not do any automatic path expansions. Functions such as expanduser() and expandvars() can be invoked explicitly when an application desires shell-like path expansion. (See also the glob module.)
The pathlib module offers high-level path objects.
All of these functions accept either only bytes or only string objects as their parameters. The result is an object of the same type, if a path or file name is returned.
Since different operating systems have different path name conventions, there are several versions of this module in the standard library. The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats. They all have the same interface:
posixpath for UNIX-style paths
ntpath for Windows paths
Changed in version 3.8: exists() , lexists() , isdir() , isfile() , islink() , and ismount() now return False instead of raising an exception for paths that contain characters or bytes unrepresentable at the OS level.
Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)) .
Changed in version 3.6: Accepts a path-like object .
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split() . Note that the result of this function is different from the Unix basename program; where basename for ‘/foo/bar/’ returns ‘bar’ , the basename() function returns an empty string ( » ).
Changed in version 3.6: Accepts a path-like object .
Return the longest common sub-path of each pathname in the sequence paths. Raise ValueError if paths contain both absolute and relative pathnames, the paths are on the different drives or if paths is empty. Unlike commonprefix() , this returns a valid path.
New in version 3.5.
Changed in version 3.6: Accepts a sequence of path-like objects .
Return the longest path prefix (taken character-by-character) that is a prefix of all paths in list. If list is empty, return the empty string ( » ).
This function may return invalid paths because it works a character at a time. To obtain a valid path, see commonpath() .
Changed in version 3.6: Accepts a path-like object .
Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split() .
Changed in version 3.6: Accepts a path-like object .
Return True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.
Changed in version 3.3: path can now be an integer: True is returned if it is an open file descriptor, False otherwise.
Changed in version 3.6: Accepts a path-like object .
Return True if path refers to an existing path. Returns True for broken symbolic links. Equivalent to exists() on platforms lacking os.lstat() .
Changed in version 3.6: Accepts a path-like object .
On Unix and Windows, return the argument with an initial component of
user replaced by that user’s home directory.
On Unix, an initial
is replaced by the environment variable HOME if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in module pwd . An initial
user is looked up directly in the password directory.
On Windows, USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial
user is handled by checking that the last directory component of the current user’s home directory matches USERNAME , and replacing it if so.
If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.
Changed in version 3.6: Accepts a path-like object .
Changed in version 3.8: No longer uses HOME on Windows.
Return the argument with environment variables expanded. Substrings of the form $name or $
On Windows, %name% expansions are supported in addition to $name and $
Changed in version 3.6: Accepts a path-like object .
Return the time of last access of path. The return value is a floating point number giving the number of seconds since the epoch (see the time module). Raise OSError if the file does not exist or is inaccessible.
os.path. getmtime ( path ) ¶
Return the time of last modification of path. The return value is a floating point number giving the number of seconds since the epoch (see the time module). Raise OSError if the file does not exist or is inaccessible.
Changed in version 3.6: Accepts a path-like object .
Return the system’s ctime which, on some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time for path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise OSError if the file does not exist or is inaccessible.
Changed in version 3.6: Accepts a path-like object .
Return the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible.
Changed in version 3.6: Accepts a path-like object .
Return True if path is an absolute pathname. On Unix, that means it begins with a slash, on Windows that it begins with a (back)slash after chopping off a potential drive letter.
Changed in version 3.6: Accepts a path-like object .
Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.
Changed in version 3.6: Accepts a path-like object .
Return True if path is an existing directory. This follows symbolic links, so both islink() and isdir() can be true for the same path.
Changed in version 3.6: Accepts a path-like object .
Return True if path refers to an existing directory entry that is a symbolic link. Always False if symbolic links are not supported by the Python runtime.
Changed in version 3.6: Accepts a path-like object .
Return True if pathname path is a mount point: a point in a file system where a different file system has been mounted. On POSIX, the function checks whether path’s parent, path /.. , is on a different device than path, or whether path /.. and path point to the same i-node on the same device — this should detect mount points for all Unix and POSIX variants. It is not able to reliably detect bind mounts on the same filesystem. On Windows, a drive letter root and a share UNC are always mount points, and for any other path GetVolumePathName is called to see if it is different from the input path.
New in version 3.4: Support for detecting non-root mount points on Windows.
Changed in version 3.6: Accepts a path-like object .
Join one or more path segments intelligently. The return value is the concatenation of path and all members of *paths, with exactly one directory separator following each non-empty part, except the last. That is, the result will only end in a separator if the last part is either empty or ends in a separator. If a segment is an absolute path (which on Windows requires both a drive and a root), then all previous segments are ignored and joining continues from the absolute path segment.
On Windows, the drive is not reset when a rooted path segment (e.g., r’\foo’ ) is encountered. If a segment is on a different drive or is an absolute path, all previous segments are ignored and the drive is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: ( c:foo ), not c:\foo .
Changed in version 3.6: Accepts a path-like object for path and paths.
Normalize the case of a pathname. On Windows, convert all characters in the pathname to lowercase, and also convert forward slashes to backward slashes. On other operating systems, return the path unchanged.
Changed in version 3.6: Accepts a path-like object .
Normalize a pathname by collapsing redundant separators and up-level references so that A//B , A/B/ , A/./B and A/foo/../B all become A/B . This string manipulation may change the meaning of a path that contains symbolic links. On Windows, it converts forward slashes to backward slashes. To normalize case, use normcase() .
On POSIX systems, in accordance with IEEE Std 1003.1 2013 Edition; 4.13 Pathname Resolution, if a pathname begins with exactly two slashes, the first component following the leading characters may be interpreted in an implementation-defined manner, although more than two leading characters shall be treated as a single character.
Changed in version 3.6: Accepts a path-like object .
Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system).
If a path doesn’t exist or a symlink loop is encountered, and strict is True , OSError is raised. If strict is False , the path is resolved as far as possible and any remainder is appended without checking whether it exists.
This function emulates the operating system’s procedure for making a path canonical, which differs slightly between Windows and UNIX with respect to how links and subsequent path components interact.
Operating system APIs make paths canonical as needed, so it’s not normally necessary to call this function.
Changed in version 3.6: Accepts a path-like object .
Changed in version 3.8: Symbolic links and junctions are now resolved on Windows.
Changed in version 3.10: The strict parameter was added.
Return a relative filepath to path either from the current directory or from an optional start directory. This is a path computation: the filesystem is not accessed to confirm the existence or nature of path or start. On Windows, ValueError is raised when path and start are on different drives.
Changed in version 3.6: Accepts a path-like object .
Return True if both pathname arguments refer to the same file or directory. This is determined by the device number and i-node number and raises an exception if an os.stat() call on either pathname fails.
Changed in version 3.2: Added Windows support.
Changed in version 3.4: Windows now uses the same implementation as all other platforms.
Changed in version 3.6: Accepts a path-like object .
Return True if the file descriptors fp1 and fp2 refer to the same file.
Changed in version 3.2: Added Windows support.
Changed in version 3.6: Accepts a path-like object .
Return True if the stat tuples stat1 and stat2 refer to the same file. These structures may have been returned by os.fstat() , os.lstat() , or os.stat() . This function implements the underlying comparison used by samefile() and sameopenfile() .
Changed in version 3.4: Added Windows support.
Changed in version 3.6: Accepts a path-like object .
Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty. Trailing slashes are stripped from head unless it is the root (one or more slashes only). In all cases, join(head, tail) returns a path to the same location as path (but the strings may differ). Also see the functions dirname() and basename() .
Changed in version 3.6: Accepts a path-like object .
Split the pathname path into a pair (drive, tail) where drive is either a mount point or the empty string. On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path.
On Windows, splits a pathname into drive/UNC sharepoint and relative path.
If the path contains a drive letter, drive will contain everything up to and including the colon:
If the path contains a UNC path, drive will contain the host name and share, up to but not including the fourth separator:
Changed in version 3.6: Accepts a path-like object .
Split the pathname path into a pair (root, ext) such that root + ext == path , and the extension, ext, is empty or begins with a period and contains at most one period.
If the path contains no extension, ext will be » :
If the path contains an extension, then ext will be set to this extension, including the leading period. Note that previous periods will be ignored:
Leading periods of the last component of the path are considered to be part of the root:
Changed in version 3.6: Accepts a path-like object .
True if arbitrary Unicode strings can be used as file names (within limitations imposed by the file system).