Удалить файл в Python
Стандартное решение для удаления файла в Python использует метод os.remove() функция. Он принимает путь, который должен быть файлом; в противном случае возникает исключение.
Чтобы обработать случай, когда указанный путь является каталогом, вы должны:
1. Перед удалением проверьте наличие файла:
2. Перехватите исключение с помощью try-except:
2. Использование os.unlink() функция
В качестве альтернативы вы можете использовать os.unlink() функция для удаления файла, который семантически идентичен os.remove() функция.
3. Использование pathlib.Path.unlink() функция
Начиная с Python 3.4, рассмотрите возможность использования Path.unlink() функцию от pathlib модуль для удаления файла или символической ссылки.
Это все об удалении файла в Python.
Оценить этот пост
Средний рейтинг 5 /5. Подсчет голосов: 20
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования
Содержание папки
Модуль стандартной библиотеки 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 и переложите в неё данные файлы.
Для тестирования вашей программы положите в репозиторий файлы и папки с соответствующими именами. Файлы должны быть пустыми, если не указано обратного.
Delete (Remove) Files and Directories in Python
In this tutorial, you’ll learn how to delete files or directories in Python.
After reading this tutorial, you’ll learn: –
- Deleting file using the os module and pathlib module
- Deleting files from a directory
- Remove files that match a pattern (wildcard)
- Delete empty directory
- Delete content of a directory (all files and sub directories)
Sometimes we need to delete files from a directory that is no longer needed. For example, you are storing monthly inventory data in a file. You may want to delete any existing data files before creating a new data file each month.
Also, after some time, the application needs to delete its old log files.
In this tutorial, we will use the following Python functions to delete files and folders.
Function | Description |
---|---|
os.remove(‘file_path’) | Removes the specified file. |
os.unlink(‘file_path’) | Removes the specified file. Useful in UNIX environment. |
pathlib.Path(«file_path»).unlink() | Delete the file or symbolic link in the mentioned path |
os.rmdir(’empty_dir_path’) | Removes the empty folder. |
pathlib.Path(empty_dir_path).rmdir() | Unlink and delete the empty folder. |
shutil.rmtree(‘dir_path’) | Delete a directory and the files contained in it. |
Functions to delete files and folders
Note:
- All above functions delete files and folders permanently.
- The pathlib module was added in Python 3.4. It is appropriate when your application runs on a different operating systems.
Table of contents
How to Delete a File in Python
Python provides strong support for file handling. We can delete files using different methods and the most commonly used one is the os.remove() method. Below are the steps to delete a file.
-
Find the path of a file
We can delete 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. And A relative path includes the current directory and then the file name.
For example, /home/Pynative/reports/samples.txt is an absolute path to discover the samples.txt.
The OS module in Python provides methods to interact with the Operating System in Python. The remove () method in this module is used to remove/delete a file path.
First, import the os module and Pass a file path to the os.remove(‘file_path’) function to delete a file from a disk
Import the shutil module and pass the directory path to shutil.rmtree(‘path’) function to delete a directory and all files contained in it.
Example: Remove File in Python
The following code explains how to delete a file named “sales_1.txt”.
Let’s assume we want to delete the sales_1.txt file from the E:\demos\files\ directory. Right now, this directory contains the following files:
- sales_1.txt
- sales_2.csv
- profits.txt
- revenue.txt
Remove file with relative path
Remove file with absolute path
Our code deleted two files. Here is a list of the remaining files in our directory:
- profits.txt
- revenue.txt
Before deleting a file
After deleting a file
Understand the os.remove() method
Syntax:
Pass file path to the os.remove(‘file_path’) function to delete a file from a disk
The following are the parameters that we need to pass.
- path – A relative or absolute path for the file object generally in string format.
- dir_fd – A directory representing the location of the file. The default value is none and this value is ignored in the case of an absolute path.
If the passed file path is a directory, an OSError will be raised
Check if File Exist Before Deleting It
A FileNotFoundError will be raised if the file is not found in the path so it is advisable to check if the file exists before deleting it.
This can be achieved in two ways:
- os.path.exists(«file path») function to check if file exists.
- Use exception handling.
Example 1:
Note: Exception handling is recommended over file check because the file could be removed or changed in between. It is the Pythonic way to delete a file that may or may not exist.
Example 2: Exception handling
Remove File Using os.unlink() method
If you are using the UNIX operating system use the unlink() method available in the OS module, which is similar to the remove() except that it is more familiar in the UNIX environment.
- path – A relative or absolute path for the file object generally in string format.
- dir_fd – A directory representing the location of the file. The default value is none and this value is ignored in the case of an absolute path.
Let us see the code for deleting the file “profits.txt” which is in the current execution path.
Pathlib Module to Remove File
The pathlib module offers classes representing filesystem paths with semantics appropriate for different operating systems. Thus, whenever we need to work with files in multiple environments, we can use the pathlib module.
The pathlib module was added in Python 3.4. The pathlib.path.unlink() method in the pathlib module is used to remove the file in the mentioned path.
Also, it takes one extra parameter, namely missing_ok=False . If the parameter is set to True, then the pathlib module ignores the File Not Found Error. Otherwise, if the path doesn’t exist, then the FileNotFoundError will be raised.
Let us see the code for deleting the file “profits.txt” which is present in the current execution path.
- Import a pathlib module
- Use pathlib.Path() method to set a file path
- Next, to delete a file call the unlink() method on a given file path.
Delete all Files from a Directory
Sometimes we want to delete all files from a directory without deleting a directory. Follow the below steps to delete all files from a directory.
-
using os.listdir(path) 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 access each file one by one
- Delete each file using the os.remove()
Example:
Delete an Empty Directory (Folder) using rmdir()
While it is always the case that a directory has some files, sometimes there are empty folders or directories that no longer needed. We can delete them using the rmdir() method available in both the os module and the pathlib module.
Using os.rmdir() method
In order to delete empty folders, we can use the rmdir() function from the os module.
The following are the parameters that we need to pass to this method.
- path – A relative or absolute path for the directory object generally in string format.
- dir_fd – File directory. The default value is none, and this value is ignored in the case of an absolute path.
Note: In case if the directory is not empty then the OSError will be thrown.
Output
Use pathlib.Path.rmdir()
The rmdir() method in the pathlib module is also used to remove or delete an empty directory.
- First set the path for the directory
- Next, call the rmdir() method on that path
Let us see an example for deleting an empty directory called ‘Images’.
Delete a Non-Empty Directory using shutil
Sometimes we need to delete a folder and all files contained in it. Use the rmtree() method of a shutil module to delete a directory and all files from it. See delete a non-empty folder in Python.
The Python shutil module helps perform high-level operations in a file or collection of files like copying or removing content.
Parameters:
- path – The directory to delete. The symbolic links to a directory are not acceptable.
- ignore_errors – If this flag is set to true, then the errors due to failed removals will be ignored. If set to true, the error should be handler by the function passed in the one error attribute.
Note: The rmtree() function deletes the specified folder and all its subfolders recursively.
Consider the following example for deleting the folder ‘reports’ that contains image files and pdf files.
Output
Get the proper exception message while deleting a non-empty directory
In order to get the proper exception message we can either handle it in a separate function whose name we can pass in the oneerror parameter or by catching it in the try-except block.
Final code: To delete File or directory
Deleting Files Matching a Pattern
For example, you want to delete files if a name contains a specific string.
The Python glob module, part of the Python Standard Library, is used to find the files and folders whose names follow a specific pattern.
The glob.glob() method returns a list of files or folders that matches the pattern specified in the pathname argument.
This function takes two arguments, namely pathname, and recursive flag ( If set to True it will search files recursively in all subfolders)
We can use the wildcard characters for the pattern matching, and the following is the list of the wildcard characters used in the pattern matching.
- Asterisk ( * ): Matches zero or more characters
- Question Mark ( ? ) matches exactly one character
- We can specify a range of alphanumeric characters inside the [] .
Example: Deleting Files with Specific Extension
On certain occasions, we have to delete all the files with a particular extension.
- Use glob() method to find all text files in a folder
- Use for loop to iterate all files
- In each iteration, delete single file.
Let us see few examples to understand how to use this to delete files that match a specific pattern.
Example
Delete file whose name starts with specific string
Delete file whose name contains a specific letters
We can give a range of characters as the search string by enclosing them inside the square brackets ( [] ).
The following example will show how to delete files whose name contains characters between a-g.
Deleting Files Matching a Pattern from all Subfolders
While the glob() function finds files inside a folder, it is possible to search for files inside the subfolders using the iglob() function which is similar to the glob() function.
The iglob() function returns iterator options with the list of files matching a pattern inside the folder and its subfolder.
We need to set the recursive flag to True when we search for the files in subdirectories. After the root folder name, we need to pass ** for searching inside the subdirectories.
Output
Conclusion
Python provides several modules for removing files and directories.
To delete Files: –
- Use os.remove() and os.unlink() functions to delete a single file
- Use pathlib.Path.unlink() to delete a file if you use Python version > 3.4 and application runs on different operating systems.
To delete Directories
- Use os.rmdir() or pathlib.Path.rmdir() to delete an empty directory
- use the shutil.rmtree() to recursively delete a directory and all files from it.
Take due care before removing files or directories because all the above functions delete files and folders permanently.
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.
Как удалить файлы в Python?
В нашем руководстве по работе с файлами в Python мы узнали, как управлять ими. В этом руководстве мы узнаем, как удалять файлы в Python.
Предположим, что после успешного создания файла мы выполняем с ним некоторые операции, такие как чтение и запись. Как только мы закончили использовать файл для анализа различных наборов данных, возможно, в некоторых случаях он нам не понадобится в будущем.
Давайте посмотрим на различные способы, с помощью которых мы можем удалять файлы в Python.
1 Использование модуля os
Модуль os в Python предоставляет несколько простых в использовании методов, с помощью которых мы можем удалить или удалить файл, а также пустой каталог. Внимательно посмотрите на приведенный ниже код:
Здесь мы использовали оператор if-else, чтобы избежать исключения, которое может возникнуть, если каталог файлов не существует. Метод isfile() проверяет существование файла с именем файла — ‘new_file.txt’.
Опять же, модуль os предоставляет нам другой метод, rmdir() , который можно использовать для удаления или удаления пустого каталога. Например:
Примечание: каталог должен быть пустым. Если он содержит какой-либо контент, метод возвращает ошибку OSerror.
2 Использование модуля shutil
Shutil — это еще один метод удаления файлов, который позволяет пользователю легко удалить файл или его полный каталог (включая все его содержимое).
rmtree() — это метод модуля shutil, который рекурсивно удаляет каталог и его содержимое. Давайте посмотрим, как его использовать:
Для вышеупомянутого кода удален каталог / test /. И самое главное, все содержимое внутри каталога также удаляется.
3 Использование модуля pathlib
pathlib — это встроенный модуль Python, доступный для Python 3.4+.
В приведенном выше примере метод path() используется для получения пути к файлу, тогда как метод unlink() используется для отмены связи или удаления файла по указанному пути.
Метод unlink() работает с файлами. Если указан каталог, возникает ошибка OSError. Чтобы удалить каталог, мы можем прибегнуть к одному из ранее обсужденных методов.