How to Delete a File in Python (2024)

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.

How to Delete a File in Python (2024)

FAQs

How do you delete a file in Python? ›

remove() One of the most straightforward ways to delete a file in Python is by using the os module's remove() function. This method is concise and well-suited for simple file deletion tasks. import os file_path = 'example.

What is delete () in Python? ›

Definition and Usage

The del keyword is used to delete objects. In Python everything is an object, so the del keyword can also be used to delete variables, lists, or parts of a list etc.

How to delete a PDF file in Python? ›

We can use functions from Python's built-in os module to delete files and empty folders.
  1. os. remove() will delete a file.
  2. os. rmdir() will delete an empty folder.
Apr 15, 2023

How do I delete an empty file in Python? ›

Remove Empty Files using os.

The delete_empty_files_using_walk() function takes this path as an argument and starts routing through all the possible combinations of folders, subfolders, and files for each path, it checks if the path represents a file and if it is empty. If yes, then it deletes the file.

What is safe delete in Python? ›

The Safe Delete refactoring lets you safely remove files from the source code. To make sure that deletion is safe, PyCharm looks for the usages of the file being deleted. If such usages are found, you can explore them and make the necessary corrections in your code before the symbol is actually deleted.

How do I delete a file in terminal? ›

Deleting files (rm command)
  1. To delete the file named myfile, type the following: rm myfile.
  2. To delete all the files in the mydir directory, one by one, type the following: rm -i mydir/* After each file name displays, type y and press Enter to delete the file. Or to keep the file, just press Enter.

Why can't I delete in Python? ›

Additionally, Python is an interpreted language, which means that code is executed immediately as it is written. Once a line of code has been executed, it may not be possible to "undo" or "delete" that action without modifying the code itself.

How to delete text in Python? ›

Removing characters from a string in Python can be done using replace(), translate() or re.sub() among other methods. During the data cleaning process, you might have encountered situations where you've needed to remove specific characters from a string.

What is remove () Python? ›

What is Remove in Python? Python's built-in method, remove (), removes specific elements from a list. It searches for and eliminates the first occurrence of a specified element. It operates based on the element's value, not its index.

How do you remove a file type in Python? ›

Removing File Extensions in Python

Thankfully, there are two different ways to do this: using the os module or using the pathlib module. Both modules provide ways to manipulate paths and filenames, so they are handy when removing file extensions. The os module provides a function called os. path.

How do I delete a PDF file? ›

Click the page thumbnail of any page or pages you want to delete, then click the “Delete” icon to remove the page or pages from the file. Apply changes: After clicking the “Delete” icon, click “o*k” to apply changes to remove the pages.

How do I delete a folder and file inside Python? ›

There are multiple ways to delete a file in Python but the best ways are the following:
  1. os.remove() removes a file.
  2. os.unlink() removes a file. ...
  3. shutil.rmtree() deletes a directory and all its contents.
  4. pathlib.Path.unlink() deletes a single file The pathlib module is available in Python 3.4 and above.
Aug 9, 2011

How do I uninstall a Python file? ›

You can look for and delete a Python application by doing the following:
  1. Click Go at the top of the screen.
  2. Click Applications in the drop-down menu.
  3. Look for an application with "Python" in the name (e.g., "Python 3.6").
  4. Select the application if you find it.
  5. Click File, then click Move to Trash.
Aug 1, 2024

How do you delete a file after execution in Python? ›

remove(__file__) : This line uses the os. remove() function to delete a file. In this case, it uses the __file__ variable, which represents the path to the currently executing script. So, the script instructs the operating system to delete its own file.

What is the rm command in Python? ›

The rm command with the -r and -f flags is used to recursively delete a directory and its contents. It can be used even if some of the files or directories are write-protected or have other permissions that prevent normal deletion. The rm -rf command below deletes a directory called thedirectory and all its contents.

Top Articles
What Time Does the London Stock Market Open?
Leverage- Meaning, Types & Importance
Pollen Count Centreville Va
Custom Screensaver On The Non-touch Kindle 4
Http://N14.Ultipro.com
Maria Dolores Franziska Kolowrat Krakowská
Junk Cars For Sale Craigslist
Rainbird Wiring Diagram
How Much Is 10000 Nickels
Holly Ranch Aussie Farm
Dr Lisa Jones Dvm Married
Www Movieswood Com
The Haunted Drury Hotels of San Antonio’s Riverwalk
83600 Block Of 11Th Street East Palmdale Ca
Thayer Rasmussen Cause Of Death
今月のSpotify Japanese Hip Hopベスト作品 -2024/08-|K.EG
R/Afkarena
Craigslist In Flagstaff
Vintage Stock Edmond Ok
Hyvee Workday
Kringloopwinkel Second Sale Roosendaal - Leemstraat 4e
Never Give Up Quotes to Keep You Going
Busted Mcpherson Newspaper
Parc Soleil Drowning
Aes Salt Lake City Showdown
Mtr-18W120S150-Ul
What Are The Symptoms Of A Bad Solenoid Pack E4od?
Panola County Busted Newspaper
Scripchat Gratis
Plost Dental
Bolsa Feels Bad For Sancho's Loss.
Skymovieshd.ib
Little Einsteins Transcript
Elanco Rebates.com 2022
Craigslist/Phx
Fairwinds Shred Fest 2023
Tamilrockers Movies 2023 Download
Joplin Pets Craigslist
Soulstone Survivors Igg
Chatropolis Call Me
Yogu Cheshire
Urban Blight Crossword Clue
Brandon Spikes Career Earnings
Differential Diagnosis
Gamestop Store Manager Pay
Vintage Stock Edmond Ok
Chr Pop Pulse
Fine Taladorian Cheese Platter
Join MileSplit to get access to the latest news, films, and events!
Cars & Trucks near Old Forge, PA - craigslist
Where Is Darla-Jean Stanton Now
Latest Posts
Article information

Author: Van Hayes

Last Updated:

Views: 6473

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Van Hayes

Birthday: 1994-06-07

Address: 2004 Kling Rapid, New Destiny, MT 64658-2367

Phone: +512425013758

Job: National Farming Director

Hobby: Reading, Polo, Genealogy, amateur radio, Scouting, Stand-up comedy, Cryptography

Introduction: My name is Van Hayes, I am a thankful, friendly, smiling, calm, powerful, fine, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.