Указание Python сохранить файл .txt в определенном каталоге в Windows и Mac
Например, мой компьютер запускает файл Python с моего рабочего стола. Я хочу, чтобы он сохранил весь текстовый файл в папке моих документов, а не на моем рабочем столе. Как это сделать в script следующим образом?
2 ответа
Просто используйте абсолютный путь при открытии дескриптора файла для записи.
Вы можете объединить это с os.path.abspath() , как описано в ответе Брайана, чтобы автоматически получить путь к папке «Документы пользователя». Ура!
Используйте os.path.join для объединения пути к каталогу Documents с completeName (имя файла?), предоставленным пользователем.
Если вы хотите, чтобы каталог Documents относился к домашнему каталогу пользователя, вы можете использовать что-то вроде:
Copy Files and Directories in Python
In this Python tutorial, you’ll learn how to use various functions available in the os, shutil, and subprocess modules to copy files and folders from one location to another.
After reading this article, you’ll learn: –
- How to copy files in Python using shutil module’s copy() , copy2() , copyfiles() , copyfileobj() methods
- The OS and subprocess module to copy files using the underlying operating system’s shell command ( copy in Windows or cp in UNIX.)
- How to copy all files from a directory
- Copy an entire directory recursively
Table of contents
Steps to Copy a File in Python
Python provides strong support for file handling. We can copy single and multiple files using different methods and the most commonly used one is the shutil.copy() method. The below steps show how to copy a file from one folder to another.
-
Find the path of a file
We can copy a file using both relative path and absolute path. The path is the location of the file on the disk.
An absolute path contains the complete directory list required to locate the file. For example, /home/Pynative/samples.txt is an absolute path to discover the samples.txt.
The shutil module offers several functions to perform high-level operations on files and collections of files. The copy() function in this module is used to copy files from one directory to another.
First, import the shutil module and Pass a source file path and destination directory path to the copy(src, dst) function.
Suppose you want to copy all files from one directory to another, then use the os.listdir() function to list all files of a source folder, then iterate a list using a for loop and copy each file using the copy() function.
The shutil.copytree(src, dst) recursively copy an entire directory tree rooted at src to a directory named dst and return the destination directory
Example: Copy Single File
In this example, we are copying the profit.txt file from the report folder to the account folder.
Copy All Files From A Directory
Sometimes we want to copy all files from one directory to another. Follow the below steps to copy all files from a directory.
- Store the source and destination directory path into two variables
- Get the list of all files present in the source folder using the os.listdir() function. It returns a list containing the names of the files and folders in the given directory.
- Iterate over the list using a for loop to get the individual filenames
- In each iteration, concatenate the current file name with the source folder path
- Now use the shutil.copy() method to copy the current file to the destination folder path.
Example:
Output:
Copy Entire Directory
Sometimes we need to copy an entire folder, including all files and subfolders contained in it. Use the copytree() method of a shutil module to copy the directory recursively.
- This method recursively copy an entire directory tree rooted at src to a directory named dst and return the destination directory.
- The dirs_exist_ok dictates whether to raise an exception in case dst or any missing parent directory already exists.
- Use the copy_function parameter to pass any of the four functions the shutil module provides to copy files.
Example: Let’s to how to copy the report directory and all its content into an account directory.
Shutil Module to Copy files
Python shutil module offers many high-end functions to perform copy and removal of files.
These functions provide an optimized way to copy files and thereby save time in performing the unnecessary task of opening, reading, writing, and closing the files when there is no processing required in that file.
The shutil module offers the following four functions to copy files.
| Function | Description |
|---|---|
| shutil.copyfileobj() | Copy the file object from a source to the destination. (Need to open both source and destination path) |
| shutil.copyfile() | Copy the contents of one file to another file. The metadata of the file will not be copied. |
| shutil.copy() | copy the contents of the source file to the destination file along with metadata. |
| shutil.copy2() | copy the additional metadata namely timestamps of the source file to the destination |
shutil copy methods
To decide which function to use for copying a file, we have to consider the following points.
- For example, If your application uses the shared resources, you should copy a file in blocking mode instead of asynchronously.
- Platform portability. If your application runs on a different operating system, you must write a code that will run on a different OS without any issue.
- The function is resource-intensive as some copy functions involve opening the file, reading the contents, writing and closing the file. so choose as per your need
- Do you want to copy metadata along with file content?
The shutil.copyfile() method
The copyfile() method is used to copy the contents of one file to another file. The metadata of the file will not be copied.
- fsrc : The source file location (path) whose contents need to be copied.
- fdst : The destination file location (path) where the contents from the source file will be pasted.
- follow_symlinks : The default value for this is true. If it is false and the source file location is a symbolic link then a new symbolic link will be created instead of copying from the file.
Note: The metadata of the file will not be copied while using this method.
Example:
Our code copied the ‘profit.txt’ file in the destination directory. Here is a list of the files present in the destination directory:
- profit.txt
- revenue.txt
Use the os.listdir(dst_folder) function to list all files present in the destination directory to verify the result.
The following are the important points
- Both the source and destination should be a file. If the destination is a directory then IsADirectoryError will be raised.
- If the source and destination point to the same file then the SameFileError will be raised.
- If the destination exists but with a different name compared to the source file then the contents of the destination file will be overwritten.
To avoid the above errors always wrap your code in the try-except block. Refer the following example.
Output
The shutil.copy() method
The shutil module has one more method to copy the file called copy() method which will copy the contents of the source file to the destination file.
Similar to the copyfile() method this method will throw the ‘ SameFileError ‘ if the source and destination point to the same file.
Consider the following example where we try to copy the file ‘profit.txt’ from the source src to the destination dst directory.
Note: If the source file is not found in the location then the copy() method can’t be executed and an IOError will be raised. If the destination folder is not writable then ‘ PermissionError ‘ will be raised.
copy() vs copyfiles()
While the copy() and copyfile() methods in the shutil module work the same way in copying files from one location to another there are some significant differences between them.
If the destination path is ‘file’ or ‘directory’ then the copy() method will create a file in the name of the source file.
- The copy() method saves the additional metadata information about the permission modes from the source to the destination file. The copyfile() doesn’t save any metadata information.
- As the copy() method makes one additional call to save the permission modes; it is slower when compared to the copyfile () method.
The copy() method calls the copyfile() and copymode() inside its implementation internally. But the copyfile () only calls the copyfileobj() inside its implementation
The shutil.copy2() method
In shutil there is one more method called copy2() which could be used to copy the file from one location to another.
While the copy() and the copy2() methods both copy the contents of the file along with the metadata there are two significant differences between these two methods.
- The copy2() method can be used to copy the additional metadata namely timestamps of the source to the destination. This is in addition to the permission modes which the copy() method saves.
- The copy2() method calls the copystat() method to get the timestamp information while the copy() method saves the permission modes from the copymode()
The scenarios that this method throws the ‘SameFileError’ are similar to the copy() method.We can see how to use this method to copy the file named ‘Sample.txt’ from the source to the destination.
Ouput
The shutil.copyfileobj() method
The copyfileobj() method is used to copy the file object from source to destination location.
In addition to the source and destination location, we can pass the buffer size, indicating the portion of the file that needs to be copied. The default value for this is 16 KB.
- fsrc : The source file location (path) whose contents need to be copied.
- fdst : The destination file location (path) where the contents from the source file will be pasted.
- length : The buffer size representing the number of bytes kept in memory during the copy process. The default size that the system used is 16KB.
Let us see an example to profit.txt from the report folder to the account folder.
Example:
Copy Files Using OS Module
The Python os module provides functions that are interoperable in different os. We have to use the underlying copy commands specific to the particular operating system. The methods are portable across different operating systems.
Copying files using os.popen() method
The popen() method opens a pipe to execute a command that we pass on the file object. This method opens a file object in the read or the write mode. The read is a default mode.
- cmd : The command that will be executed in the open file object.
- mode : The mode with which a file can be opened and default mode is r .
- buffering : The number of bytes that will be stored in the buffer. If mentioned as 0 then it will not save any.
The underlying shell command for copying is copy for windows and cp for UNIX environment.
Let us see how to use this method to copy a file called profit.txt from the source folder to the destination folder.
On Unix:
Copying file using os.system() method
The system() method is again used to execute the script in the shell or an OS command. The return value is the exit status of the command.
- This is implemented by calling the Standard C function system() , and has the same limitations.
- On Unix, the return value is the exit status of the process encoded in the format specified for wait() .
- On Windows, the return value is that returned by the system shell after running the command.
command : Takes the single argument command which is the underlying shell command that will be executed.
Let us see how to use this method to copy a file called sample.txt from the source folder to the destination folder.
Subprocess Module to Copy Files
The subprocess module is used to execute/launch a new subprocess from our application, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several older modules and functions:
The subprocess.call() method
This method could be used to execute any command that is passed as an argument to this method and the return value would be end status of the command that was executed.
- args : Required for all calls and should be a string, or a sequence of program arguments. The call() method actually runs the command mentioned by the args.
- stdin , stdout and stderr specify the executed program’s standard input, standard output, and standard error respectively.
- shell : If set to true, the specified command will be executed through the shell.
Output
Copying Files using subprocess.check_output() method
The check_output() method is again used to execute external commands and capture its output. This is very similar to the call() method with a similar set of arguments.
universal_newlines : If this value is True then all line endings will be converted to ‘\n’ as described for the universal newlines ‘U’ mode argument to open() .
Output
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
Содержание папки
Модуль стандартной библиотеки 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 и переложите в неё данные файлы.
Для тестирования вашей программы положите в репозиторий файлы и папки с соответствующими именами. Файлы должны быть пустыми, если не указано обратного.
Pathlib — манипуляция путями, создание и удаление папок и файлов

Модуль Pathlib в Python упрощает работу с файлами и папками. Он доступен в Python 3.4 и более поздних версиях. Pathlib сочетает в себе лучшее из модулей файловой системы Python — os, os.path, glob и так далее.
Содержание статьи
В Python большинство скриптов предполагает работу с файловыми системами. Следовательно, неизбежно взаимодействие с названиями файлов и путями. Именно для этого в Python есть модуль Pathlib, который содержит полезные функции для выполнения задач, связанных с файлами. Pathlib предоставляет удобный для чтения и простой способ создания путей, представляя пути файловой системы в виде надлежащих объектов. Модуль позволяет создавать код, который можно переносить между платформами.
В данной статье мы подробно изучим модуль Pathlib с помощью различных примеров.
Концепт пути и директории в Python
Перед началом подробного рассмотрения модуля Pathlib важно разобраться в разнице между главными концептами темы — путем (path) и директорией (directory).
- Путь используется для идентификации файла. Путь предоставляет необязательную последовательность названий директорий, в конце которой значится конечное имя файла, а также его расширение;
- Расширение названия файла предоставляет некоторую информацию о формате/содержимом файла. Модуль Pathlib может работать как с абсолютными, так и с относительными путями;
- Абсолютный путь начинается с корневой директории и определяет полное дерево каталогов;
- Относительный путь, как следует из названия, является путем к файлу относительно другого файла или директории, обычно текущей;
- Директория представляет собой запись пути в файловой системе и включает название файла, время создания, размер, владельца и так далее.
Модуль Pathlib в Python занимается задачами, связанными с путями, такими как создание новых путей из названий файлов и других путей, проверка различных свойств путей, создание файлов и папок по определенным путям.
Есть вопросы по Python?
На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!
Telegram Чат & Канал
Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!
Паблик VK
Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!
Как использовать модуль Pathlib?
Для работы с Pathlib в Python требуется импортировать все классы данного модуля, используя следующую команду:
В качестве первого задания давайте извлечем текущую рабочую директорию и домашнюю директорию объектов, используя следующий код:
Вместо импорта всех классов можно использовать import pathlib . В таком случае, задействуя классы внутри модуля, требуется добавлять через pathlib .
Зачем использовать модуль Pathlib?
Если вы некоторое время работали с языком Python, у вас может возникнуть вопрос. Зачем нужен модуль Pathlib, когда уже есть модули os , os.path , glob и прочие? Это хороший вопрос. Давайте попробуем ответить на него, разобрав следующий пример.
Допустим, мы хотим создать файл под названием «output/output.xlsx» в текущем рабочем каталоге. Следующий код пытается сделать это с помощью модуля os.path . Также используются функции os.getcwd и os.path.join .
Хотя код работает, он выглядит несколько странно, плохо читается, в нем сложно уловить суть. Представьте, как данный код выглядел бы, если бы мы хотели создать новый файл внутри глубоко расположенной директории.
Данный код можно переписать, используя модуль Pathlib:
Такой формат проще укладывается в голове. В Pathlib функция Path.cwd() используется для получения текущего рабочего каталога, а оператор / используется вместо os.path.join для объединения частей пути в составной объект пути.
Шаблон вложенности функций в модуле os.path заменяется классом Path модуля Pathlib, что представляет путь через объединение методов и атрибутов. Умная перегрузка оператора / делает код читабельным и простым в обращении.
Другое преимущество метода, предоставляемого модулем Pathlib, заключается в том, что объект Path создается вместо строкового представления пути. У этого объекта есть несколько удобных методов, что имеют значительное преимущество перед работой с необработанными строками, которые представляют пути.
Создание и удаление папок через Pathlib
Классический модуль os.path используется только для манипуляции строками пути. Чтобы что-то сделать с путем, например, создать директорию, нам нужен модуль os . Модуль os предоставляет набор функций для работы с файлами и каталогами, например: mkdir для создания директории, rename для переименования, а getsize для получения ее размера.
Давайте напишем некоторые из этих операций с помощью модуля os , а затем перепишем тот же код с помощью модуля Pathlib.
Пример кода, написанный с использованием модуля os :
Если мы используем объекты path модуля Pathlib для достижения той же функциональности, конечный код будет читабельнее и легче для понимания:
В модуле os сложновато найти утилиты, связанные с путем. Модуль Pathlib решает эту проблему, заменяя утилиты модуля os методами объектов путя. Давайте попробуем разобраться в этом на примере следующего кода:
Здесь функция generate_data() принимает путь к файлу в качестве параметра и записывает данные в другой путь. Однако, если файл, который передается в качестве параметра, не изменяется, так как в последний раз была выполнена функция generate_data() , генерируется пустой файл. В этом случае пустой файл заменяется предыдущей версией файла.