Как удалять файлы и каталоги в Python
Python имеет несколько встроенных модулей, которые позволяют удалять файлы и каталоги.
В этом руководстве объясняется, как удалять файлы и каталоги с помощью функций из модулей os , pathlib и shutil .
Удаление файлов
В Python вы можете использовать os.remove() , os.unlink() , pathlib.Path.unlink() для удаления одного файла.
Модуль os обеспечивает переносимый способ взаимодействия с операционной системой. Модуль доступен как для Python 2, так и для 3.
Чтобы удалить один файл с помощью os.remove() , передайте путь к файлу в качестве аргумента:
os.remove() и os.unlink() семантически идентичны:
Если указанный файл не существует, FileNotFoundError ошибка FileNotFoundError . И os.remove() и os.unlink() могут удалять только файлы, но не каталоги. Если указанный путь указывает на каталог, они IsADirectoryError ошибку IsADirectoryError .
Для удаления файла требуется разрешение на запись и выполнение для каталога, содержащего файл. В противном случае вы получите ошибку PermissionError .
Чтобы избежать ошибок при удалении файлов, вы можете использовать обработку исключений, чтобы перехватить исключение и отправить соответствующее сообщение об ошибке:
Модуль pathlib доступен в Python 3.4 и выше. Если вы хотите использовать этот модуль в Python 2, вы можете установить его с помощью pip. pathlib предоставляет объектно-ориентированный интерфейс для работы с путями файловой системы для различных операционных систем.
Чтобы удалить файл с pathlib модуля pathlib , создайте объект Path указывающий на файл, и вызовите метод unlink() для объекта:
pathlib.Path.unlink() , os.remove() и os.unlink() также можно использовать для удаления символической ссылки .
Сопоставление с образцом
Вы можете использовать модуль glob для сопоставления нескольких файлов на основе шаблона. Например, чтобы удалить все файлы .txt каталоге /tmp , вы должны использовать что-то вроде этого:
Чтобы рекурсивно удалить все файлы .txt в каталоге /tmp и всех подкаталогах в нем, передайте аргумент recursive=True функции glob() и используйте шаблон « ** »:
Модуль pathlib включает две функции glob, glob() и rglob() для сопоставления файлов в данном каталоге. glob() сопоставляет файлы только в каталоге верхнего уровня. rglob() сопоставляет все файлы в каталоге и всех подкаталогах. В следующем примере кода удаляются все файлы .txt каталоге /tmp :
Удаление каталогов (папок)
В Python вы можете использовать os.rmdir() и pathlib.Path.rmdir() для удаления пустого каталога и shutil.rmtree() для удаления непустого каталога.
В следующем примере показано, как удалить пустой каталог:
В качестве альтернативы вы можете удалить каталоги с pathlib модуля pathlib :
Модуль shutil позволяет выполнять ряд высокоуровневых операций с файлами и каталогами.
С помощью функции shutil.rmtree() вы можете удалить указанный каталог, включая его содержимое:
Аргумент, переданный в shutil.rmtree() не может быть символической ссылкой на каталог.
Выводы
Python предоставляет несколько модулей для работы с файлами.
Мы показали вам, как использовать os.remove() , os.unlink() , pathlib.Path.unlink() для удаления одного файла, os.rmdir() и pathlib.Path.rmdir() для удаления пустого файла. directory и shutil.rmtree() для рекурсивного удаления каталога и всего его содержимого.
Будьте особенно осторожны при удалении файлов или каталогов, потому что после удаления файла его будет нелегко восстановить.
Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.
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 os.unlink() Method

Python os.unlink() method is an efficient way of removing a file path or directory. This method is syntactically similar to the os.remove() method.
Syntax of os.unlink() Method
Please enable JavaScript
Parameters
Return
In the execution process, this method does not return any value.
Example 1: Use the os.unlink() Method to Remove or Delete a File Path
An OSError might occur while using the os.unlink() method due to invalid or inaccessible processes and paths.
Example 2: Handling Errors in the os.unlink() Method
Note that the os.unlink() method cannot remove a directory. If the parameter entered is a directory, then the IsADirectoryError error is thrown.
Alternatively, the os.rmdir() method can be used to remove a valid path or directory.
Example 3: Use Conditional Statements With the os.unlink() Method
Alternatively, you can use the os.remove method in the above code.
Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.
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 наиболее полезных операций по работе с файлами. Как вы могли убедиться, все они укладываются в несколько строк кода, поэтому не представляют абсолютно никакой сложности. Если вы с ними не знакомы, то надеемся, что эта статья послужит для вас кратким руководством в процессе работы с файлами.