Содержание папки
Модуль стандартной библиотеки os (от «operation system») предоставляет множество полезных функций для произведения системных вызовов. Одна из базовых функций этого модуля — os.listdir .
С точки зрения операционной системы нет разницы между файлом, папкой или другим подобным объектом, типа ссылки. Поэтому os.listdir() возвращает список как файлов, так и папок. Обратите внимание, что порядок элементов возвращаемого списка не регламентируется, если вам нужно их отсортировать не забудьте сделать это:
Работа с путями к файлам и папкам
Модуль os содержит подмодуль os.path , который позволяет работать с путями файлов и папок. Импортировать этот модуль отдельно не нужно, достаточно выполнить import os .
Присоединение одной части пути к другой
Работа с путями к файлам и папкам как с простыми строками чревата множеством ошибок и может создать проблемы при переносе программы между различными операционными системами. Правильный путь объединить две части пути — это использование os.path.join :
Извлечение имени файла из пути
Функция os.path.split совершает обратное действие — отрезает имя файла или ниже лежащей папки от пути:
Извлечение расширения
Кроме того, может пригодиться функция os.path.splitext , котоая отрезает расширение файла:
Проверка типа файла
Кроме прочего, модуль os.path содержит функции для проверки существования файла и для определения его типа:
Манипуляции с файлами и папками
Производите все манипуляции с файлами с осторожностью, придерживайтесь правила «семь раз отмерь — один раз отрежь». Не забывайте программно производить все возможные проверки перед выполнением операций.
Создание файла
Нет ничего проще, чем создать пустой файл, достаточно открыть несуществующий файл с флагом ‘x’ :
Конечно, можно было бы использовать флаг ‘w’ , но тогда уже существующий файл был бы стёрт. С флагом ‘x’ open либо создаст новый файл, либо выбросит ошибку.
Создание папки
Для создания новой папки используйте os.mkdir(name) . Эта функция выбросит ошибку, если по указанному пути уже существует файл или папка. Если вам нужно создать сразу несколько вложенных папок, то смотрите функцию os.makedirs(name, exist_ok=False) .
Перемещение и переименование
Для удобной манипуляции с файлами и папками в стандартной библиотеки Python существует специальный модуль shutil . Функция shutil.move(source, destination) позволяет вам переместить любой файл или папку (даже непустую). Обратите внимание, что если destination — это уже существующая папка, то файл/папка будет перемещена внутрь неё, в остальных случаях файл/папка будут скопированы точно по нужному адресу. В случае успеха, функция вернёт новое местоположение файла. Если destination существует и не является папкой, то будет выброшена ошибка.
Как же переименовать файл? Несмотря на то, что os содержит специальную функцию для переименования, нужно понимать, что в рамках одной файловой системы перемещение и переименование — это одно и то же. Когда вы переименовываете файл, его содержимое не переписывается на носителе в другое место, просто файловая система теперь обозначает его положение другим путём.
Копирование
Скопировать файл можно с помощью функции shutil.copy(source, destination) . Правила расположения копии будут те же, что и при использовании shutil.move , за тем исключением, что если destination существует и не является файлом, то он будет заменён и ошибки это не вызовет.
Скопировать папку для операционной системы сложнее, ведь мы всегда хотим скопировать не только папку, но и её содержимое. Для копирования папок используйте shutil.copytree(source, destination) . Обратите внимание, что для этой функции destination всегда должно быть путём конечного расположения файлов и не может быть уже существующей папкой.
Удаление
Удалить файл можно с помощью функции os.remove , а пустую папку с помощью функции os.rmdir .
А вот для удаления папки с содержимым вновь понадобится shutil . Для удаления такой папки используйте shutil.rmtree .
Будьте осторожны, команды удаления стирают файл, а не перемещают его в корзину, вне зависимости от операционной системы! После такого удаления восстановить файл может быть сложно или вовсе невозможно.
Домашняя работа
- В текущей папке лежат файлы с расширениями .mp3 , .flac и .oga . Создайте папки mp3 , flac , oga и положите туда все файлы с соответствующими расширениями.
- В текущей папке лежит две других папки: vasya и mila , причём в этих папках могут лежать файлы с одинаковыми именами, например vasya/kursovaya.doc и mila/kursovaya.doc . Скопируйте все файлы из этих папок в текущую папку назвав их следующим образом: vasya_kursovaya.doc , mila_test.pdf и т.п.
- В текущей папке лежат файлы следующего вида: S01E01.mkv , S01E02.mkv , S02E01.mkv и т.п., то есть все файлы начинаются с S01 или S02 . Создайте папки S01 и S02 и переложите туда соответствующие файлы.
- В текущей папке лежат файлы вида 2019-03-08.jpg , 2019-04-01.jpg и т.п. Отсортируйте файлы по имени и переименуйте их в 1.jpg , 2.jpg , …, 10.jpg , и т.д.
- В текущей папке лежат две другие папки: video и sub . Создайте новую папку watch_me и переложите туда содержимое указанных папок (сами папки класть не надо).
- В текущей папке лежат файлы типа Nina_Stoletova.jpg , Misha_Perelman.jpg и т.п. Переименуйте их переставив имя и фамилию местами.
- В текущей папке лежит файл list.tsv , в котором с новой строки написаны имена некоторых других файлов этой папки. Создайте папку list и переложите в неё данные файлы.
Для тестирования вашей программы положите в репозиторий файлы и папки с соответствующими именами. Файлы должны быть пустыми, если не указано обратного.
shutil — High-level file operations¶
The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal. For operations on individual files, see also the os module.
Even the higher-level file copying functions ( shutil.copy() , shutil.copy2() ) cannot copy all file metadata.
On POSIX platforms, this means that file owner and group are lost as well as ACLs. On Mac OS, the resource fork and other metadata are not used. This means that resources will be lost and file type and creator codes will not be correct. On Windows, file owners, ACLs and alternate data streams are not copied.
Directory and files operations¶
Copy the contents of the file-like object fsrc to the file-like object fdst. The integer length, if given, is the buffer size. In particular, a negative length value means to copy the data without looping over the source data in chunks; by default the data is read in chunks to avoid uncontrolled memory consumption. Note that if the current file position of the fsrc object is not 0, only the contents from the current file position to the end of the file will be copied.
shutil. copyfile ( src , dst , * , follow_symlinks = True ) ¶
Copy the contents (no metadata) of the file named src to a file named dst and return dst in the most efficient way possible. src and dst are path-like objects or path names given as strings.
dst must be the complete target file name; look at copy() for a copy that accepts a target directory path. If src and dst specify the same file, SameFileError is raised.
The destination location must be writable; otherwise, an OSError exception will be raised. If dst already exists, it will be replaced. Special files such as character or block devices and pipes cannot be copied with this function.
If follow_symlinks is false and src is a symbolic link, a new symbolic link will be created instead of copying the file src points to.
Raises an auditing event shutil.copyfile with arguments src , dst .
Changed in version 3.3: IOError used to be raised instead of OSError . Added follow_symlinks argument. Now returns dst.
Changed in version 3.4: Raise SameFileError instead of Error . Since the former is a subclass of the latter, this change is backward compatible.
Changed in version 3.8: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section.
This exception is raised if source and destination in copyfile() are the same file.
New in version 3.4.
Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. src and dst are path-like objects or path names given as strings. If follow_symlinks is false, and both src and dst are symbolic links, copymode() will attempt to modify the mode of dst itself (rather than the file it points to). This functionality is not available on every platform; please see copystat() for more information. If copymode() cannot modify symbolic links on the local platform, and it is asked to do so, it will do nothing and return.
Raises an auditing event shutil.copymode with arguments src , dst .
Changed in version 3.3: Added follow_symlinks argument.
Copy the permission bits, last access time, last modification time, and flags from src to dst. On Linux, copystat() also copies the “extended attributes” where possible. The file contents, owner, and group are unaffected. src and dst are path-like objects or path names given as strings.
If follow_symlinks is false, and src and dst both refer to symbolic links, copystat() will operate on the symbolic links themselves rather than the files the symbolic links refer to—reading the information from the src symbolic link, and writing the information to the dst symbolic link.
Not all platforms provide the ability to examine and modify symbolic links. Python itself can tell you what functionality is locally available.
If os.chmod in os.supports_follow_symlinks is True , copystat() can modify the permission bits of a symbolic link.
If os.utime in os.supports_follow_symlinks is True , copystat() can modify the last access and modification times of a symbolic link.
If os.chflags in os.supports_follow_symlinks is True , copystat() can modify the flags of a symbolic link. ( os.chflags is not available on all platforms.)
On platforms where some or all of this functionality is unavailable, when asked to modify a symbolic link, copystat() will copy everything it can. copystat() never returns failure.
Please see os.supports_follow_symlinks for more information.
Raises an auditing event shutil.copystat with arguments src , dst .
Changed in version 3.3: Added follow_symlinks argument and support for Linux extended attributes.
Copies the file src to the file or directory dst. src and dst should be path-like objects or strings. If dst specifies a directory, the file will be copied into dst using the base filename from src. If dst specifies a file that already exists, it will be replaced. Returns the path to the newly created file.
If follow_symlinks is false, and src is a symbolic link, dst will be created as a symbolic link. If follow_symlinks is true and src is a symbolic link, dst will be a copy of the file src refers to.
copy() copies the file data and the file’s permission mode (see os.chmod() ). Other metadata, like the file’s creation and modification times, is not preserved. To preserve all file metadata from the original, use copy2() instead.
Raises an auditing event shutil.copyfile with arguments src , dst .
Raises an auditing event shutil.copymode with arguments src , dst .
Changed in version 3.3: Added follow_symlinks argument. Now returns path to the newly created file.
Changed in version 3.8: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section.
Identical to copy() except that copy2() also attempts to preserve file metadata.
When follow_symlinks is false, and src is a symbolic link, copy2() attempts to copy all metadata from the src symbolic link to the newly created dst symbolic link. However, this functionality is not available on all platforms. On platforms where some or all of this functionality is unavailable, copy2() will preserve all the metadata it can; copy2() never raises an exception because it cannot preserve file metadata.
copy2() uses copystat() to copy the file metadata. Please see copystat() for more information about platform support for modifying symbolic link metadata.
Raises an auditing event shutil.copyfile with arguments src , dst .
Raises an auditing event shutil.copystat with arguments src , dst .
Changed in version 3.3: Added follow_symlinks argument, try to copy extended file system attributes too (currently Linux only). Now returns path to the newly created file.
Changed in version 3.8: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section.
This factory function creates a function that can be used as a callable for copytree() ‘s ignore argument, ignoring files and directories that match one of the glob-style patterns provided. See the example below.
shutil. copytree ( src , dst , symlinks = False , ignore = None , copy_function = copy2 , ignore_dangling_symlinks = False , dirs_exist_ok = False ) ¶
Recursively copy an entire directory tree rooted at src to a directory named dst and return the destination directory. All intermediate directories needed to contain dst will also be created by default.
Permissions and times of directories are copied with copystat() , individual files are copied using copy2() .
If symlinks is true, symbolic links in the source tree are represented as symbolic links in the new tree and the metadata of the original links will be copied as far as the platform allows; if false or omitted, the contents and metadata of the linked files are copied to the new tree.
When symlinks is false, if the file pointed by the symlink doesn’t exist, an exception will be added in the list of errors raised in an Error exception at the end of the copy process. You can set the optional ignore_dangling_symlinks flag to true if you want to silence this exception. Notice that this option has no effect on platforms that don’t support os.symlink() .
If ignore is given, it must be a callable that will receive as its arguments the directory being visited by copytree() , and a list of its contents, as returned by os.listdir() . Since copytree() is called recursively, the ignore callable will be called once for each directory that is copied. The callable must return a sequence of directory and file names relative to the current directory (i.e. a subset of the items in its second argument); these names will then be ignored in the copy process. ignore_patterns() can be used to create such a callable that ignores names based on glob-style patterns.
If exception(s) occur, an Error is raised with a list of reasons.
If copy_function is given, it must be a callable that will be used to copy each file. It will be called with the source path and the destination path as arguments. By default, copy2() is used, but any function that supports the same signature (like copy() ) can be used.
If dirs_exist_ok is false (the default) and dst already exists, a FileExistsError is raised. If dirs_exist_ok is true, the copying operation will continue if it encounters existing directories, and files within the dst tree will be overwritten by corresponding files from the src tree.
Raises an auditing event shutil.copytree with arguments src , dst .
Changed in version 3.3: Copy metadata when symlinks is false. Now returns dst.
Changed in version 3.2: Added the copy_function argument to be able to provide a custom copy function. Added the ignore_dangling_symlinks argument to silence dangling symlinks errors when symlinks is false.
Changed in version 3.8: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section.
New in version 3.8: The dirs_exist_ok parameter.
Delete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception.
On platforms that support the necessary fd-based functions a symlink attack resistant version of rmtree() is used by default. On other platforms, the rmtree() implementation is susceptible to a symlink attack: given proper timing and circumstances, attackers can manipulate symlinks on the filesystem to delete files they wouldn’t be able to access otherwise. Applications can use the rmtree.avoids_symlink_attacks function attribute to determine which case applies.
If onerror is provided, it must be a callable that accepts three parameters: function, path, and excinfo.
The first parameter, function, is the function which raised the exception; it depends on the platform and implementation. The second parameter, path, will be the path name passed to function. The third parameter, excinfo, will be the exception information returned by sys.exc_info() . Exceptions raised by onerror will not be caught.
Raises an auditing event shutil.rmtree with arguments path , dir_fd .
Changed in version 3.3: Added a symlink attack resistant version that is used automatically if platform supports fd-based functions.
Changed in version 3.8: On Windows, will no longer delete the contents of a directory junction before removing the junction.
Changed in version 3.11: The dir_fd parameter.
Indicates whether the current platform and implementation provides a symlink attack resistant version of rmtree() . Currently this is only true for platforms supporting fd-based directory access functions.
New in version 3.3.
Recursively move a file or directory (src) to another location (dst) and return the destination.
If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics.
If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied to dst using copy_function and then removed. In case of symlinks, a new symlink pointing to the target of src will be created in or as dst and src will be removed.
If copy_function is given, it must be a callable that takes two arguments src and dst, and will be used to copy src to dst if os.rename() cannot be used. If the source is a directory, copytree() is called, passing it the copy_function() . The default copy_function is copy2() . Using copy() as the copy_function allows the move to succeed when it is not possible to also copy the metadata, at the expense of not copying any of the metadata.
Raises an auditing event shutil.move with arguments src , dst .
Changed in version 3.3: Added explicit symlink handling for foreign filesystems, thus adapting it to the behavior of GNU’s mv. Now returns dst.
Changed in version 3.5: Added the copy_function keyword argument.
Changed in version 3.8: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section.
Changed in version 3.9: Accepts a path-like object for both src and dst.
Return disk usage statistics about the given path as a named tuple with the attributes total, used and free, which are the amount of total, used and free space, in bytes. path may be a file or a directory.
New in version 3.3.
Changed in version 3.8: On Windows, path can now be a file or directory.
Change owner user and/or group of the given path.
user can be a system user name or a uid; the same applies to group. At least one argument is required.
See also os.chown() , the underlying function.
Raises an auditing event shutil.chown with arguments path , user , group .
New in version 3.3.
Return the path to an executable which would be run if the given cmd was called. If no cmd would be called, return None .
mode is a permission mask passed to os.access() , by default determining if the file exists and executable.
When no path is specified, the results of os.environ() are used, returning either the “PATH” value or a fallback of os.defpath .
On Windows, the current directory is always prepended to the path whether or not you use the default or provide your own, which is the behavior the command shell uses when finding executables. Additionally, when finding the cmd in the path, the PATHEXT environment variable is checked. For example, if you call shutil.which("python") , which() will search PATHEXT to know that it should look for python.exe within the path directories. For example, on Windows:
New in version 3.3.
Changed in version 3.8: The bytes type is now accepted. If cmd type is bytes , the result type is also bytes .
This exception collects exceptions that are raised during a multi-file operation. For copytree() , the exception argument is a list of 3-tuples (srcname, dstname, exception).
Platform-dependent efficient copy operations¶
Starting from Python 3.8, all functions involving a file copy ( copyfile() , copy() , copy2() , copytree() , and move() ) may use platform-specific “fast-copy” syscalls in order to copy the file more efficiently (see bpo-33671). “fast-copy” means that the copying operation occurs within the kernel, avoiding the use of userspace buffers in Python as in “ outfd.write(infd.read()) ”.
On macOS fcopyfile is used to copy the file content (not metadata).
On Linux os.sendfile() is used.
On Windows shutil.copyfile() uses a bigger default buffer size (1 MiB instead of 64 KiB) and a memoryview() -based variant of shutil.copyfileobj() is used.
If the fast-copy operation fails and no data was written in the destination file then shutil will silently fallback on using less efficient copyfileobj() function internally.
Changed in version 3.8.
copytree example¶
An example that uses the ignore_patterns() helper:
This will copy everything except .pyc files and files or directories whose name starts with tmp .
Another example that uses the ignore argument to add a logging call:
rmtree example¶
This example shows how to remove a directory tree on Windows where some of the files have their read-only bit set. It uses the onerror callback to clear the readonly bit and reattempt the remove. Any subsequent failure will propagate.
Archiving operations¶
New in version 3.2.
Changed in version 3.5: Added support for the xztar format.
High-level utilities to create and read compressed and archived files are also provided. They rely on the zipfile and tarfile modules.
shutil. make_archive ( base_name , format [ , root_dir [ , base_dir [ , verbose [ , dry_run [ , owner [ , group [ , logger ] ] ] ] ] ] ] ) ¶
Create an archive file (such as zip or tar) and return its name.
base_name is the name of the file to create, including the path, minus any format-specific extension. format is the archive format: one of “zip” (if the zlib module is available), “tar”, “gztar” (if the zlib module is available), “bztar” (if the bz2 module is available), or “xztar” (if the lzma module is available).
root_dir is a directory that will be the root directory of the archive, all paths in the archive will be relative to it; for example, we typically chdir into root_dir before creating the archive.
base_dir is the directory where we start archiving from; i.e. base_dir will be the common prefix of all files and directories in the archive. base_dir must be given relative to root_dir. See Archiving example with base_dir for how to use base_dir and root_dir together.
root_dir and base_dir both default to the current directory.
If dry_run is true, no archive is created, but the operations that would be executed are logged to logger.
owner and group are used when creating a tar archive. By default, uses the current owner and group.
logger must be an object compatible with PEP 282, usually an instance of logging.Logger .
The verbose argument is unused and deprecated.
Raises an auditing event shutil.make_archive with arguments base_name , format , root_dir , base_dir .
This function is not thread-safe when custom archivers registered with register_archive_format() are used. In this case it temporarily changes the current working directory of the process to perform archiving.
Changed in version 3.8: The modern pax (POSIX.1-2001) format is now used instead of the legacy GNU format for archives created with format="tar" .
Changed in version 3.10.6: This function is now made thread-safe during creation of standard .zip and tar archives.
Return a list of supported formats for archiving. Each element of the returned sequence is a tuple (name, description) .
By default shutil provides these formats:
zip: ZIP file (if the zlib module is available).
tar: Uncompressed tar file. Uses POSIX.1-2001 pax format for new archives.
gztar: gzip’ed tar-file (if the zlib module is available).
bztar: bzip2’ed tar-file (if the bz2 module is available).
xztar: xz’ed tar-file (if the lzma module is available).
You can register new formats or provide your own archiver for any existing formats, by using register_archive_format() .
shutil. register_archive_format ( name , function [ , extra_args [ , description ] ] ) ¶
Register an archiver for the format name.
function is the callable that will be used to unpack archives. The callable will receive the base_name of the file to create, followed by the base_dir (which defaults to os.curdir ) to start archiving from. Further arguments are passed as keyword arguments: owner, group, dry_run and logger (as passed in make_archive() ).
If given, extra_args is a sequence of (name, value) pairs that will be used as extra keywords arguments when the archiver callable is used.
description is used by get_archive_formats() which returns the list of archivers. Defaults to an empty string.
shutil. unregister_archive_format ( name ) ¶
Remove the archive format name from the list of supported formats.
shutil. unpack_archive ( filename [ , extract_dir [ , format ] ] ) ¶
Unpack an archive. filename is the full path of the archive.
extract_dir is the name of the target directory where the archive is unpacked. If not provided, the current working directory is used.
format is the archive format: one of “zip”, “tar”, “gztar”, “bztar”, or “xztar”. Or any other format registered with register_unpack_format() . If not provided, unpack_archive() will use the archive file name extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised.
Raises an auditing event shutil.unpack_archive with arguments filename , extract_dir , format .
Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of the path specified in the extract_dir argument, e.g. members that have absolute filenames starting with “/” or filenames with two dots “..”.
Changed in version 3.7: Accepts a path-like object for filename and extract_dir.
Registers an unpack format. name is the name of the format and extensions is a list of extensions corresponding to the format, like .zip for Zip files.
function is the callable that will be used to unpack archives. The callable will receive the path of the archive, followed by the directory the archive must be extracted to.
When provided, extra_args is a sequence of (name, value) tuples that will be passed as keywords arguments to the callable.
description can be provided to describe the format, and will be returned by the get_unpack_formats() function.
shutil. unregister_unpack_format ( name ) ¶
Unregister an unpack format. name is the name of the format.
Return a list of all registered formats for unpacking. Each element of the returned sequence is a tuple (name, extensions, description) .
By default shutil provides these formats:
zip: ZIP file (unpacking compressed files works only if the corresponding module is available).
tar: uncompressed tar file.
gztar: gzip’ed tar-file (if the zlib module is available).
bztar: bzip2’ed tar-file (if the bz2 module is available).
xztar: xz’ed tar-file (if the lzma module is available).
You can register new formats or provide your own unpacker for any existing formats, by using register_unpack_format() .
Archiving example¶
In this example, we create a gzip’ed tar-file archive containing all files found in the .ssh directory of the user:
The resulting archive contains:
Archiving example with base_dir¶
In this example, similar to the one above, we show how to use make_archive() , but this time with the usage of base_dir. We now have the following directory structure:
In the final archive, please_add.txt should be included, but do_not_add.txt should not. Therefore we use the following:
Listing the files in the resulting archive gives us:
Querying the size of the output terminal¶
Get the size of the terminal window.
For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used.
When COLUMNS or LINES is not defined, which is the common case, the terminal connected to sys.__stdout__ is queried by invoking os.get_terminal_size() .
If the terminal size cannot be successfully queried, either because the system doesn’t support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. fallback defaults to (80, 24) which is the default size used by many terminal emulators.
The value returned is a named tuple of type os.terminal_size .
See also: The Single UNIX Specification, Version 2, Other Environment Variables.
10 самых продуктивных техник для работы с файлами в Python
Какой бы проект вы ни разрабатывали, вам не избежать работы с файлами либо на компьютере, либо на сервере. И неудивительно, поскольку они являются самыми распространёнными контейнерами для хранения взаимосвязанной и обычно структурированной информации. При этом многим приходится выискивать конкретные операции, связанные с обработкой файлов. Поэтому мы решили посвятить данную статью 10 наиболее эффективным техникам для работы с файлами в Python.
1. Показ текущей директории
Чтобы узнать текущую рабочую директорию, мы можем просто ввести функцию getcwd() модуля os, как показано ниже:
Данный код также демонстрирует возможность использования модуля pathlib для получения текущей рабочей директории. Обратите внимание, что для выполнения операций с файлами именно этот модуль является предпочтительным вариантом, и в статье вас ждёт немало примеров его употребления. Однако, если у вас устаревшая версия Python (< 3.4), то вам придётся использовать модуль os .
2. Создание новой директории
Для создания новой директории можно применить функцию mkdir() , которая выполнит эту операцию по конкретно заданному пути. Если вы просто укажете имя новой директории, то она будет создана в текущем каталоге:
Однако, если вы намерены создать новую директорию с несколькими вложенными уровнями (имеется в виду наличие одной папки внутри другой), то вам необходимо использовать функцию makedirs() . Обратимся к простому примеру:
Если же у вас последние версии Python (≥ 3.4), то для решения вышеуказанной задачи можно воспользоваться преимуществом модуля pathlib . При этом он способен не только создавать поддиректории, но также при необходимости работать с каталогами, отсутствующими в пути. Рассмотрим пример:
Имейте в виду, что попытка повторного выполнения вышеприведённого кода может вызвать проблемы — вы не сможете создать новую директорию, если такая уже существует. Стоит отметить, что эта проблема решается путём присвоения аргументу exist_ok значения True , как показано выше. А вот значение False , установленное для него по умолчанию, не позволит повторно создать уже существующую директорию и приведёт к ошибке.
3. Удаление директорий и файлов
По завершении операций с файлами или папками, возможно, потребуется их удалить, чтобы упорядочить ресурсы компьютера. Для удаления файла в модуле os применяется функция remove() , а для удаления папки — функция rmdir() . Попытка же удалить директорию с помощью remove() вызовет ошибку. Рассмотрим применение этих функций:
При использовании модуля pathlib за удаление файла отвечает метод unlink() , а за удаление директории — rmdir() . Обратите внимание, что они оба являются методами экземпляра объекта Path .
4. Получение списка файлов
В процессе обработки данных для аналитики или проектов МО вам потребуется получить список файлов в определённой директории. Зачастую их имена соответствуют определённому шаблону. Допустим, мы хотим найти все файлы .txt в директории. Далее рассмотрим, как это можно сделать с помощью метода glob() с объектом Path . Обратите внимание, что данный метод создаёт генератор с возможностью итерации. Следующий код наглядно демонстрирует создание генератором списка путей файлов:
Как вариант, также удобно использовать модуль glob напрямую, как показано ниже. Он располагает аналогичной функциональностью, создавая списки имён файлов, с которыми впоследствии можно работать. Заметьте, что Path.glob() создаёт пути. Оба метода будут работать в большинстве сценариев, таких как чтение и запись файлов.
5. Перемещение и копирование файлов
Перемещение и копирование — одна из стандартных задач управления файлами, которая довольно легко решается в Python. Для перемещения вы просто переименовываете файл, заменяя его старую директорию целевой. Предположим, необходимо переместить все файлы .txt в другую папку. В следующем примере кода мы увидим, как это можно сделать с помощью модуля pathlib:
Копирование же можно выполнить при помощи функциональности, доступной в shutil, ещё одном полезном модуле из стандартной библиотеки для операций с файлами. Здесь за это отвечает функция copy() , в которой исходный и целевой файлы указываются в виде строк. Ниже вы увидите простой пример. Конечно, вы можете объединить функции copy() и glob() для работы с группой файлов, соответствующих одному паттерну.
6. Проверка директории/файла
На самом деле, эта операция уже много раз встречалась в вышеприведённых примерах. В них для проверки того, существует ли конкретный путь, применялся метод exists() . При условии положительного ответа он возвращает True , в противном случае — False . Примечательно, что эта функция доступна в обоих модулях, os и pathlib, но с разными сигнатурами. Рассмотрим соответствующие примеры их применения:
В модуле pathlib можно также проверить, является ли путь директорией или файлом с готовыми к вызову функциями. Обратимся к следующему примеру:
7. Получение информации о файле
При работе с файлами во многих сценариях возникает необходимость извлечения их имён. С объектом Path это просто как дважды два, и вы уже были свидетелями его применения. Можно просто извлечь атрибут name файлового объекта Path . Если же вам нужно узнать только имя без расширения, то извлекать следует атрибут stem . Следующий фрагмент кода демонстрирует соответствующие случаи применения:
В отдельных случаях вам потребуется узнать расширение файла, с которым вы работаете. Чаще всего можно воспользоваться атрибутом suffix файлового объекта Path , как показано ниже:
Если необходимо получить больше информации о файле, например, его размер и время изменения, то для этого в нашем распоряжении есть метод stat() , принцип действия которого аналогичен os.stat() , знакомого тем, кто привык работать с модулем os.
8. Чтение файлов
Одна из важнейших операций с файлами — считывание их данных. В конце концов, содержимое файла является, вероятно, единственной причиной его появления. Самый традиционный способ состоит в создании файлового объекта с помощью встроенной функции open() . По умолчанию она откроет файл в режиме чтения и будет работать с его данными как с текстом. Рассмотрим пример:
Этот код демонстрирует самые распространённые способы чтения содержимого. Если вы знаете, что ваш файл включает немного данных, можете считать их все за раз с помощью метода read() . Но если он очень крупный, то следует рассмотреть вариант с генератором, роль которого выполняет файловый объект. Он обрабатывает данные построчно и тем самым экономно расходует память, обходясь без загрузки всех данных при применении read() .
Как уже ранее упоминалось, функция open() по умолчанию работает с содержимым файла как с текстом. Однако в случае с бинарными файлами необходимо явно задать данное условие. Например, вместо ‘r’ следует ввести ‘rb’ . Это требование также относится и к записи файлов, о чём мы поговорим далее. Ещё один непростой момент связан с кодировкой файла. Во многих случаях функция open() сможет выполнить эту операцию за нас, и большинство файлов, с которыми мы работаем, будут в кодировке “utf-8”. Если же вы обрабатываете файлы, применяя другие форматы кодировки, вам следует установить аргумент encoding .
9. Запись файлов
Для записи данных можно опять же создать файловый объект, открыв файл в режиме записи ( ‘w’ ) или дозаписи ( ‘a’ ). В первом случае при записи данных в файл его старое содержимое удаляется, а во втором — данные добавляются в конец файла. Рассмотрим пример работы этих двух режимов в следующем фрагменте кода.
Этот код подтверждает, что мы можем записывать данные в двух режимах: записи и дозаписи. Обратили вы внимание или нет, но каждый раз при открытии файла использовалась инструкция with . Объясняется это тем, что она создаёт контекст для обработки файла и помогает закрыть файловый объект по завершении операций. Если же вовремя этого не сделать, то открытый файловый объект может повредиться.
10. Архивирование и разархивирование файлов
При работе с большим числом файлов может потребоваться их архивирование для долгосрочного хранения или временной передачи. Соответствующие возможности предоставляются модулем zipfile. Для архивирования файлов функцией ZipFile() создаётся файловый объект zip, что напоминает случай с функцией open() , поскольку обе эти функции предусматривают создание файлового объекта, управляемого контекстным менеджером (вспоминаете применение инструкции with ?). Обратимся к фрагменту кода с простым примером:
Вы можете получить zip-файл из внешнего источника, и вам потребуется извлечь из него файлы. Чтобы не усложнять, допустим, что мы распаковываем их в текущую директорию. Обратите внимание на то, что имена файлов в zip-файле совпадают с содержащимися в директории, вследствие чего последние будут перезаписаны без предупреждения. Поэтому вам следует рассмотреть вариант извлечения содержимого zip-файла в отдельную папку, где такой проблемы перезаписи не возникнет.
Заключение
Итак, в данной статье мы рассмотрели 10 наиболее полезных операций по работе с файлами. Как вы могли убедиться, все они укладываются в несколько строк кода, поэтому не представляют абсолютно никакой сложности. Если вы с ними не знакомы, то надеемся, что эта статья послужит для вас кратким руководством в процессе работы с файлами.
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 с содержимым, готовым к запуску.