- Python Delete File – How to Remove Files and Folders
- What We’ll Cover
- How to Delete Files with the OS Module
- How to Delete Files with the Pathlib Module
- How to Delete Empty Folders with the OS Module
- How to Delete Empty Folders with the Pathlib Module
- How to Delete a Non-Empty with the shutil Module
- Conclusion
- Как удалять файлы и каталоги в Python с помощью модулей os и shutil
- Удаление файла
- Удаление папки
- Проверка существования файла или папки перед удалением
- Обработка ошибок при удалении
- Заключение
Python Delete File – How to Remove Files and Folders
Kolade Chris
Many programming languages have built-in functionalities for working with files and folders. As a rich programming language with many exciting functionalities built into it, Python is not an exception to that.
Python has the OS and Pathlib modules with which you can create files and folders, edit files and folders, read the content of a file, and delete files and folders.
In this article, I’ll show you how to delete files and folders with the OS module.
What We’ll Cover
How to Delete Files with the OS Module
To delete any file with the OS module, you can use it’s remove() method. You then need to specify the path to the particular file inside the remove() method. But first, you need to bring in the OS module by importing it:
import os os.remove('path-to-file')
This code removes the file questions.py in the current folder:
import os os.remove('questions.py')
If the file is inside another folder, you need to specify the full path including the file name, not just the file name:
import os os.remove('folder/filename.extension')
The code below shows how I removed the file faq.txt inside the textFiles folder:
import os os.remove('textFiles/faq.txt')
To make things better, you can check if the file exists first before removing it:
import os # Extract the file path to a variable file_path = 'textFiles/faq.txt' #check if the file exists with path.exists() if os.path.exists(file_path): os.remove('textFiles/faq.txt') print('file deleted') else: print("File does not exists")
You can also use try..except for the same purpose:
import os try: os.remove('textFiles/faq.txt') print('file deleted') except: print("File doesn't exist")
How to Delete Files with the Pathlib Module
The pathlib module is a module in Python’s standard library that provides you with an object-oriented approach to working with file system paths. You can also use it to work with files.
The pathlib module has an unlink() method you can use to remove a file. You need to get the path to the file with pathlib.Path() , then call the unlink() method on the file path:
import pathlib # get the file path try: file_path = pathlib.Path('textFiles/questions.txt') file_path.unlink() print('file deleted') except: print("File doesn't exist")
How to Delete Empty Folders with the OS Module
The OS module provides a rmdir() method with which you can delete a folder.
But the way you delete an empty folder is not the same way you delete a folder with files or subfolders in it. Let’s see how you can delete empty folders first.
Here’s how I deleted an empty client folder:
import os try: os.rmdir('client') print('Folder deleted') except: print("Folder doesn't exist")
If you attempt to delete a folder that has files or subfolders inside it, you’ll get the Directory not empty error :
import os os.rmdir('textFiles') # OSError: [Errno 66] Directory not empty: 'textFiles'
How to Delete Empty Folders with the Pathlib Module
With the pathlib module, you can extract the path of the folder you want to delete into a variable and call rmdir() on that variable:
import pathlib # get the folder path try: folder_path = pathlib.Path('docs') folder_path.rmdir() print('Folder deleted') except: print("Folder doesn't exist")
To delete a folder that has subfolders and files in it, you have to delete all the files first, then call os.rmdir() or path.rmdir() on the now empty folder. But instead of doing that, you can use the shutil module. I will show you this soon.
How to Delete a Non-Empty with the shutil Module
The shutil module has a rmtree() method you can use to remove a folder and its content – even if it contains multiple files and subfolders.
The first thing you need to do is to extract the path to the folder into a variable, then call rmtree() on that variable.
Here’s how I deleted a folder named subTexts inside the textFiles folder:
import shutil try: folder_path = 'textFiles/subTexts' shutil.rmtree(folder_path) print('Folder and its content removed') except: print('Folder not deleted')
And here’s how I removed the whole textFiles folder (it has several files and a subfolder):
import shutil try: folder_path = 'textFiles' shutil.rmtree(folder_path) print('Folder and its content removed') # Folder and its content removed except: print('Folder not deleted')
Conclusion
This article took you through how to remove a file and empty folder with the os and pathlib modules of Python. Because you might also need to remove non-empty folders too, we took a look at how you can do it with the shutil module.
If you found the article helpful, don’t hesitate to share it with your friends and family.
Kolade Chris
Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.
If you read this far, tweet to the author to show them you care. Tweet a thanks
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.
Как удалять файлы и каталоги в Python с помощью модулей os и shutil
Удаление файлов и папок в Python может быть полезным во многих сценариях, таких как очистка временных файлов, удаление неиспользуемых файлов и т.д. В этой статье мы рассмотрим, как удалить файл или папку в Python.
Удаление файла
Для удаления файла в Python необходимо использовать модуль os . Он предоставляет функцию remove() , которая позволяет удалить файл из файловой системы. Для этого необходимо передать путь к файлу в виде строки.
Вот пример кода, который удаляет файл:
import os # Удаление файла os.remove("path/to/file.txt")
В этом примере мы использовали функцию remove() из модуля os , чтобы удалить файл file.txt , который находится в папке path/to . Вы можете заменить этот путь на свой собственный путь к файлу, который вы хотите удалить.
Удаление папки
Для удаления папки в Python необходимо использовать модуль shutil . Он предоставляет функцию rmtree() , которая удаляет папку и все ее содержимое из файловой системы.
Вот пример кода, который удаляет папку:
import shutil # Удаление папки shutil.rmtree("path/to/folder")
В этом примере мы использовали функцию rmtree() из модуля shutil , чтобы удалить папку folder , которая находится в папке path/to . Эта функция также удалит все файлы и папки, которые находятся внутри папки folder . Вы можете заменить этот путь на свой собственный путь к папке, которую вы хотите удалить.
Проверка существования файла или папки перед удалением
Перед удалением файла или папки важно проверить, существует ли он в файловой системе. Если файл или папка не существует, то функция удаления выдаст ошибку.
Для проверки существования файла или папки в Python можно использовать функцию exists() из модуля os . Она возвращает True , если файл или папка существует, и False в противном случае.
Вот пример кода, который проверяет существование файла перед его удалением:
import os # Проверка существования файла if os.path.exists("path/to/file.txt"): os.remove("path/to/file.txt") print("Файл успешно удален") else: print("Файл не существует")
В этом примере мы сначала проверяем, существует ли файл file.txt в папке path/to . Если файл существует, то мы вызываем функцию remove() из модуля os , чтобы удалить его. Если файла не существует, то мы выводим сообщение Файл не существует .
Аналогично, можно проверить существование папки перед ее удалением:
import shutil # Проверка существования папки if os.path.exists("path/to/folder"): shutil.rmtree("path/to/folder") print("Папка успешно удалена") else: print("Папка не существует")
В этом примере мы сначала проверяем, существует ли папка folder в папке path/to . Если папка существует, то мы вызываем функцию rmtree() из модуля shutil , чтобы удалить ее и все ее содержимое. Если папка не существует, то мы выводим сообщение Папка не существует .
Обработка ошибок при удалении
При удалении файлов и папок могут возникать ошибки. Например, если файл или папка защищены от записи, то функция удаления выдаст ошибку. Чтобы предотвратить сбой программы в таких случаях, необходимо использовать обработку ошибок.
Вот пример кода, который удаляет файл с обработкой ошибок:
import os # Удаление файла с обработкой ошибок try: os.remove("path/to/file.txt") print("Файл успешно удален") except OSError as e: print(f"Ошибка: - ")
В этом примере мы используем конструкцию try-except для обработки ошибок при удалении файла. Если файл успешно удален, то выводится сообщение Файл успешно удален . Если при удалении файла возникает ошибка, то выводится сообщение с описанием ошибки.
Аналогично, можно обрабатывать ошибки при удалении папки.
Заключение
Удаление файлов и папок в Python — это простой процесс, который можно выполнить с помощью модулей os и shutil . Важно проверять существование файла или папки перед удалением и обрабатывать ошибки, которые могут возникнуть при удалении.