LearnPython.com
  • Courses
  • Articles
  • Log in
  • Create free account
  • fullName

    User profile menu open Open user profile menu avatar
    avatar
    fullName
    Dashboard
    My Profile
    Payment & Billing
    Log out
MENU CLOSE
  • Courses
  • Articles
  • Dashboard
  • My Profile
  • Payment & Billing
  • Log in
  • Create free account
  • Log out 
Back to articles list Articles
10th Apr 2023 7 minutes read

How to Delete a File in Python

Author's photo
Xavier Rigoulet
  • python
See More

Need to safely delete files and directories in Python? This article will show you how!

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:

  1. 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.
  2. 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.
  3. 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.
  4. Error handling: Python provides robust error handling mechanisms that can help prevent data loss or corruption due to file deletion errors.
  5. 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.

Tags:

  • python

You may also like

Learn How to Work with Files and Directories in Python
Work more efficiently with files and directories in Python. This course will make your daily work easier.
Read more
The Python Requirements File and How to Create it
Learn what a Python requirements.txt file is, how to create it, and how to maintain it with a list of required modules.
Read more
How to Open and Run Python Files in the Terminal
Read this if you want to learn how to interact with Python files in the terminal.
Read more
Different Ways to Practice Python
Are you learning Python and wondering how to practice? In this article, we’ll give a brief overview of the different ways to practice Python.
Read more
How Do You End Scripts in Python?
Do you want to learn the different ways of terminating Python scripts? Explore them in this article.
Read more
Python Libraries Every Programming Beginner Should Know
Knowing which library to use will make your programming much easier. Here, we show you the best Python libraries for beginners.
Read more
Subscribe to our newsletter Join our monthly newsletter to be notified about the latest posts.

How Do You Write a SELECT Statement in SQL?

What Is a Foreign Key in SQL?

Enumerate and Explain All the Basic Elements of an SQL Query

Quick links

  • Pricing
  • Blog
  • Vertabelo.com

Assistance

Need assistance? Drop us a line at [email protected]

Write to us

Follow us

LearnSQL Facebook We Learn SQL Facebook Linkedin LearnPython.com We Learn SQL Youtube
go to top
Copyright ©2016-2018 Vertabelo SA All rights reserved
Vertabelo
  • Terms of service
  • Privacy policy
  • Imprint