Как проверить, существует ли файл или каталог в Python
При написании скриптов Python вы можете захотеть выполнить определенное действие, только если файл или каталог существует или нет. Например, вы можете захотеть прочитать или записать данные в файл конфигурации или создать файл, только если он уже не существует.
В Python есть много разных способов проверить, существует ли файл, и определить его тип.
В этом руководстве показаны три различных метода проверки существования файла.
Проверьте, существует ли файл
Самый простой способ проверить, существует ли файл, — это попытаться открыть файл. Этот подход не требует импорта какого-либо модуля и работает как с Python 2, так и с Python 3. Используйте этот метод, если вы хотите открыть файл и выполнить какое-либо действие.
В следующем фрагменте кода используется простой блок try-except. Мы пытаемся открыть файл filename.txt , и если файл не существует, возникает исключение IOError и IOError сообщение «Файл недоступен»:
Если вы используете Python 3, вы также можете использовать FileNotFoundError вместо исключения IOError .
При открытии файлов рекомендуется использовать ключевое слово with , которое обеспечивает правильное закрытие файла после завершения файловых операций, даже если во время операции возникает исключение. Это также делает ваш код короче, потому что вам не нужно закрывать файл с помощью функции close .
Следующий код эквивалентен предыдущему примеру:
В приведенных выше примерах мы использовали блок try-except и открывали файл, чтобы избежать состояния гонки. Условия состязания возникают, когда к одному файлу обращается более одного процесса.
Например, когда вы проверяете наличие файла, другой процесс может создать, удалить или заблокировать файл в период времени между проверкой и открытием файла. Это может привести к поломке вашего кода.
Проверьте, существует ли файл с помощью модуля os.path
Модуль os.path предоставляет несколько полезных функций для работы с os.path путей. Модуль доступен как для Python 2, так и для 3.
В контексте этого руководства наиболее важными функциями являются:
- os.path.exists(path) — возвращает true, если path — это файл, каталог или допустимая символическая ссылка.
- os.path.isfile(path) — возвращает истину, если path является обычным файлом или символической ссылкой на файл.
- os.path.isdir(path) — возвращает true, если path является каталогом или символической ссылкой на каталог.
Следующий оператор if проверяет, существует ли файл filename.txt :
Используйте этот метод, когда вам нужно проверить, существует ли файл или нет, прежде чем выполнять действие с файлом. Например, копирование или удаление файла .
Если вы хотите открыть и изменить файл, используйте предыдущий метод.
Проверьте, существует ли файл, используя модуль pathlib
Модуль pathlib доступен в Python 3.4 и выше. Этот модуль предоставляет объектно-ориентированный интерфейс для работы с путями файловой системы для различных операционных систем.
Как и в предыдущем примере, следующий код проверяет, существует ли файл filename.txt :
is_file возвращает истину, если path является обычным файлом или символической ссылкой на файл. Чтобы проверить наличие каталога, используйте метод is_dir .
Основное различие между pathlib и os.path заключается в том, что pathlib позволяет вам работать с путями как с объектами Path с соответствующими методами и атрибутами вместо обычных объектов str .
Если вы хотите использовать этот модуль в Python 2, вы можете установить его с помощью pip :
Выводы
В этом руководстве мы показали вам, как с помощью Python проверить, существует ли файл или каталог.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
Проверка наличия файла или каталога в R
Для этого примера мы создали файл myfile.txt и каталог my_test_folder .
Как проверить наличие файла?
Наличие файла легко проверить с помощью команды file.exists() из базового пакета. Посмотрите следующий пример:
Попробуем теперь с файлом, которого не существует:
Обратите внимание, что выражение if not file exists записывается также и с добавлением ! внутри оператора if вот таким образом:
Кроме того, при необходимости создать пустой файл выполняется такая команда:
Как проверить наличие каталога?
По аналогии с проверкой наличия файла, при которой используется file.exists() , наличие каталогов проверяется с помощью команды dir.exists() . Например:
Теперь выполним следующее упражнение. Проверим, есть ли каталог. Если его нет, создадим новый:
Папка my_new_folder создается в нашем рабочем каталоге.
Проверка наличия файла или каталога в Python
Для этого примера опять же используем файл myfile.txt и каталог my_test_folder .
Как проверить наличие файла?
Здесь мы будем работать с модулем os :
Кроме того, здесь задействуется модуль pathlib :
В Python есть возможность создать пустой файл с помощью команды with open(filename.txt, 'w') . Например:
При открытии файла помните о следующих режимах:
Как проверить наличие каталога?
Это, опять же, аналогично проверке наличия файла:
Каталог создается следующим образом:
Чтобы проверить, существует ли объект Path независимо или является файлом/каталогом, используется exists() :
Или с помощью модуля os :
Проверка наличия файла или каталога в Bash
Как проверить наличие файла?
Для этого примера снова используем файл myfile.txt и каталог my_test_folder . Здесь мы будем работать с флагом -f , с помощью которого проверяется наличие обычного файла, а не каталога.
Задействуем скрипт mycheck.sh , который выглядит следующим образом:
Как и ожидалось, файл существует. Теперь при необходимости создать пустой скрипт выполняется такая команда:
Как проверить наличие каталога?
Здесь используем флаг -d . Задействуем скрипт dircheck.sh :
Мы получили сообщение о том, что каталог существует.
Обратите внимание, что для создания каталога выполняется следующая команда:
Отметим также, что выражение if not содержит символ ! :
И в завершение приведем перечень необходимых флагов для проверки файлов и каталогов в Bash:
Как проверить существование файла?
Как проверить существование файла по определенному пути используя Python?
Для проверки существования заданного пути используйте функцию os.path.exists :
Но она вернет True и для файла и для директории.
os.path.isfile проверит именно на наличие файла.
Кратко: вместо if exists(): open() используйте просто open() .
Если проверка нужна, чтобы выполнить позднее какую-либо операцию с файлом, то лучше прямо выполнить эту операцию и поймать возможные ошибки (предполагая, что вы на том же уровне ошибки хотите обработать):
Предварительная проверка всё равно не гарантирует, что файл всё ещё будет существовать позднее и всё равно придётся ошибки обрабатывать.
Ответы на комментарии:
- Где блок finally в котором вы закрывается поток
finally здесь не нужен. Если код попал в except блок, то файл не открыт — нечего закрывать. В else ветке, где файл открыт, with file: конструкция всегда закрывает файл при выходе из блока (нормальном или когда исключение возникло).
- Конструкция try-exept-else многими считается плохо читаемой.
Обычно try/except не используется на том же уровне, то есть в коде используется просто:
а возможные исключения выше по стеку обрабатываются. Но если вы хотите обработать ошибку в open() на том же уровне, то вы обязаны использовать try/except ( open() сигнализирует ошибки с помощью исключений).
- Каждый раз, когда файла нет, вы вызываете прерывание ОС (на нем строится механизм обработки исключения) самостоятельно, не слишком ли это раcточительно?
Исключения выбрасываются в случае ошибки в Питоне хотите вы этого или нет. Вот реализация os.path.exists() из стандартной библиотеки:
фактически, используя open() напрямую, а не if exists(): open() мы уменьшаем количество системных вызовов.
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).