- How to Delete a File in Python
- Why Use Python to Delete a File?
- 2 Ways to Delete a File in Python
- 1. Using os.remove()
- 2. Using os.unlink()
- How to Delete a Directory in Python
- Deleting Multiple Files in Python
- Using pathlib to Work with Files
- Beyond Deleting Files in Python
- Python Delete File: How to Delete a File in Python [Recovery Is Available]
- Tip 2. Run Python Data Recovery with Data Recovery Software
- Conclusion
- Python Delete Files FAQs
How to Delete a File in Python
How do you delete a file or a bunch of files programmatically? You can do so with the help of Python. In this article, we will cover how to delete a file, a batch of files, or a directory using Python. Let’s get started – without deleting the root folder!
But first, let’s answer a basic question:
Why Use Python to Delete a File?
Python provides a simple, powerful, and platform-independent way to delete files programmatically. If you do not know how to program in Python, I recommend you look at our Python programming track to start your journey.
Using Python to delete files can be advantageous for several reasons:
- Cross-platform compatibility: Python can be run on multiple platforms (Windows, Linux, MacOS, etc.), and the same code can be used to delete files on any of these platforms.
- Easy to learn: Python is a beginner-friendly programming language with a relatively simple syntax, making it easy for new programmers to learn and use.
- Powerful libraries: Python has a vast library of pre-built modules that can simplify file operations, including file deletion. These modules can save you time and effort by providing high-level abstractions for complex file operations.
- Error handling: Python provides robust error handling mechanisms that can help prevent data loss or corruption due to file deletion errors.
- Scripting: Python is a popular scripting language; its ability to automate file deletion tasks can benefit system administrators and data analysts who need to perform routine file deletion tasks.
In summary, using Python to delete files can save time and effort while ensuring cross-platform compatibility and robust error handling. Additionally, the language’s scripting capabilities make it well-suited for automating file deletion tasks.
Let’s write some code that you can store as a Python file ( .py ) and run from your terminal when you need to delete files.
2 Ways to Delete a File in Python
1. Using os.remove()
You can delete a file using Python’s os module, which provides a remove() function that deletes the specified file.
As you can see, it’s quite straightforward. You simply supply the file path as an argument to the function:
>>> import os >>> # path of the file to be deleted >>> file_path = "/path_to_folder/example1.txt" >>> # delete the file >>> os.remove(file_path)
If the specified file does not exist, the remove() function raises a FileNotFoundError exception. Therefore, checking if the file exists before attempting to delete it is good practice. You can use the os.path.exists() function to check if a file exists. Here’s an example.
>>> import os >>> file_path = "/path_to_file" >>> if os.path.exists(file_path): . os.remove(file_path) . else: . print("File not found.")
2. Using os.unlink()
The os.unlink() function is another way to delete a file in Python. It is a synonym for the os.remove() function and behaves similarly. Here’s an example of how to use this function:
>>> import os >>> # absolute path of the file to be deleted >>> file_path = "/path_to_folder/example2.txt" >>> # delete the file >>> os.unlink(file_path)
Again, it’s a good practice to check if the file exists before attempting to delete it. You can use the os.path.exists() function.
>>> import os file_path = "/path_to_file" >>> if os.path.exists(file_path): . os.unlink(file_path) . else: . print("File not found.")
Note that os.unlink() function is only available in Unix-based systems like Linux or macOS; it may not work in Windows systems. In Windows, you can use os.remove() instead.
How to Delete a Directory in Python
In Python, you can also delete a directory using the pathlib module, which provides an object-oriented way of working with file system paths. Here are some examples of deleting a directory in Python using pathlib .
First, let’s delete an empty directory:
>>> import pathlib >>> # create a Path object for the directory to be deleted >>> dir_path = pathlib.Path("empty_dir") >>> # delete the directory >>> dir_path.rmdir()
In this example, the rmdir() method deletes the empty directory specified by the dir_path object.
To delete a non-empty directory, you can use the following example.
>>> import shutil >>> import pathlib >>> # create a Path object for the directory to be deleted >>> dir_path = pathlib.Path("/path_to_my_dir/") >>> # delete the directory and its contents recursively >>> shutil.rmtree(dir_path)
In this example, the rmtree() function from the shutil module is used to delete the non-empty directory specified by the dir_path object. The rmtree() function deletes the directory and all its contents recursively.
Note that pathlib.Path.rmdir() can only delete empty directories. If the directory contains files or other directories, you need to use shutil.rmtree() to delete the directory and its contents recursively.
Also, be careful when using shutil.rmtree() . It deletes all the contents of the directory –
including files, subdirectories, and their contents – and cannot be undone.
Deleting Multiple Files in Python
In Python, you can delete multiple files using various methods. The method you choose will depend on your use case. We can use a loop to delete files iteratively:
>>> import os >>> # directory containing the files to be deleted >>> dir_path = "/path_to_directory" >>> # list of file names to be deleted >>> file_names = ["file1.txt", "file2.txt", "file3.txt"] >>> # loop over each file name and delete the file >>> for file_name in file_names: . . . file_path = os.path.join(dir_path, file_name) . . . os.remove(file_path)
In this method, a loop is used to iterate over each file name in the list and delete the file using the os.remove() function.
Alternatively, it is also possible to use a list comprehension to delete files to achieve the same result.
We can also use the glob module to delete files:
>>> import glob >>> import os >>> # directory containing the files to be deleted >>> dir_path = "/path/to/directory" >>> # pattern for file names to be deleted >>> file_pattern = "*.txt" >>> # get a list of file paths using the glob module >>> file_paths = glob.glob(os.path.join(dir_path, file_pattern)) >>> # loop over each file path and delete the file >>> for file_path in file_paths: . . . os.remove(file_path)
In this method, the glob module is used to get a list of file paths that match a specified pattern using the glob.glob() function. The list of file paths is then passed to a loop that deletes each file using the os.remove() function.
In all these methods, it’s important to check if the file exists before attempting to delete it.
Using pathlib to Work with Files
pathlib is a module in Python’s standard library that provides an object-oriented approach to working with files and directories. The Path class in pathlib can be used to delete files using the unlink() method. Here’s an example:
>>> from pathlib import Path >>> # path to the file to be deleted >>> file_path = Path("/path_to_file.txt") >>> # delete the file using the unlink() method >>> file_path.unlink()
In this example, the Path class is used to create a Path object representing the file to be deleted. The unlink() method is then called on the Path object to delete the file. Note that the unlink() method will raise a FileNotFoundError if the file does not exist, so it’s a good idea to check if the file exists before attempting to delete it.
To delete multiple files using pathlib , you can use a loop or a list comprehension to iterate over a list of Path objects representing the files to be deleted. Here’s an example using a loop:
>>> from pathlib import Path >>> # list of file paths to be deleted >>> file_paths = [Path("/path/to/file1.txt"), Path("/path/to/file2.txt"), Path("/path/to/file3.txt")] >>> # delete each file using a loop >>> for file_path in file_paths: . file_path.unlink()
In this example, a list of Path objects representing the files to be deleted is created, and a loop is used to iterate over each file path and delete the corresponding file using the unlink() method.
Just like with the os.remove() function, using Path.unlink() to delete files can result in data loss. Double-check that you’re deleting the correct files before running your code.
I did not explicitly state any particular way to end a script in this article. In the example above, all the lines are executed; however, feel free to read more about the multiple ways to end a script in Python.
Beyond Deleting Files in Python
In this article, we learned various ways of deleting files and directories in Python using fundamental Python packages. To strengthen your knowledge, feel free to check out our course on working with files and directories in Python.
If you are looking for more ways to practice Python, you can also go through our common interview questions. And don’t forget to regularly visit LearnPython.com to keep learning.
Python Delete File: How to Delete a File in Python [Recovery Is Available]
Python is a programming language that was created in the 1980s. It is widely used today because it is easy to read and write and supports multiple platforms. Python works for web development, scientific computing, artificial intelligence, and software engineering. It is also one of the most popular languages for teaching computer programming to beginners.
The main reason why most people use Python is that it is a very versatile language that can be used for many different purposes. Additionally, Python has many libraries and frameworks that make it even more powerful. One of the most important ones is Python’s indentation rules. For example, the if statement:
Step 2. Select the wanted file or folder and click «revert» on the top left.
Tip 2. Run Python Data Recovery with Data Recovery Software
The second way to recover deleted files is using data recovery software. Python data recovery software is designed to search through all the drives on your computer for any traces of Python files and then recover them. These programs are very effective and can help you recover your deleted files quickly and easily. One of the most effective file recovery tools is EaseUS Data Recovery Wizard.
EaseUS free data recovery software is a powerful data recovery software that can be used to recover deleted files and data from Python databases. The software offers a wide range of features for deleted file recovery.
- Support various file formats, such as jpg, png, bmp, and gif.
- Restore lost data due to partition loss or damage, software crash, virus infection, and other unexpected events.
- Recover deleted files from internal and external hard drives, including FAT, NTFS, and exFAT file systems.
Overall, EaseUS Data Recovery Wizard is an excellent choice for recovering files and data deleted by Python. Follow the steps below to recover deleted Python data.
Step 1. Choose the exact file location and then click the «Scan» button to continue.
Step 2. After the process, select the «Deleted Files» and «Other Lost Files» folders in the left panel. Then, you can apply the «Filter» feature or click the «Search files or folders» button to find the deleted files.
Step 3. Click the «Recover» button and save the restored files – ideally, it should be different from the original one.
Conclusion
In conclusion, Python has a few different ways to delete a file. The most straightforward way is to use the built-in «os» module. This module provides many functions for interacting with the operating system. If you want to delete a directory and all its contents, you can use the «Shutil» module. The «Shutil» module provides high-level operations on files and directories. Finally, if you want to delete an open file, you can use the «os.unlink» function. This function deletes a single file, regardless of whether it is open or not.
If Python deletes a file you don’t want to delete, you can recover Python data with the built-in «revert» option or data recovery software.
Python Delete Files FAQs
To get additional help, read the Python-related questions and answers below.
1. How do I delete a text file in Python?
Use file. truncate() to erase the file contents of a text file
2. How to fix Python Setup.py egg_info?
- Check if Pip and Setuptools Are Installed Correctly
- Upgrade Pip to Fix Python Setup.py egg_info
- Upgrade Setuptools
- Try to Install the ez_setup
3. How do you delete a file if it already exists in Python?
There are three ways to remove a file if it exists and handle errors: