Python delete file Examples [4 Different Ways]

 

Python delete file Examples

Developers use files in python programs for different purposes. When we are working with files, one of the most important functions that we need to know about is how to delete a file. In python, there are multiple ways to delete a file. For example, we can use the os.remove() method to delete files and the os.rmdir() method to delete an empty folder. Moreover, we can also use the method to delete all the files in a folder. In this tutorial, we will learn about all these methods and will see who we can delete files in python in various ways. By the end of this tutorial, you will have a solid knowledge of the python delete file concept.

 

Example-1: Use os module to delete file

Python delete file is the concept of removing the file from a specifically required directory when the file is no longer needed for any type of usage in the programming language. In python, we can delete a file by getting access to it. os library in python helps us to get the directory of the file. os library also has built-in functions to delete files and directories. In this section, we will discuss the os library and some of its built-in functions which are useful in deleting files or directories.

Advertisement

 

The os module in Python

The os stands for the operating system, it is a module in python that provides a portable way of using operating system dependent functionality. Suppose, if we want to manipulate the path of a file, then the os library has some built-in functions which can help us. It provides functions for interacting with the operating system.

We can use the os module in python by importing it. See the following example

import os

Using this library we can create new files and directories. See the following syntax for creating new empty directory using os module.

import os
os.mkdir(“name of file")

Now let us create an empty directory using the os module. See the following example:

import os
os.mkdir("PythonTutorial")

When we run this program, it will create an empty folder named Python tutorial in the same directory. We can check also the name of the current directory by using the following program:

import os
print(os.getcwd())

This will print out the name of your current working directory. In a similar way, there are many other functions in the os module which we can use to manipulate the directories. In the following section, we will discuss some of those functionalities.

Advertisement

 

Delete file using os.remove() in Python

Python provides us with strong support for file handling. We can delete files using different methods and the most commonly used one is the os.remove() method. We can use this method to remove or delete a file either through the absolute path or through a relative path. Absolute path means the complete directory list required to locate the file while relative path means the current directory and then the name of a  file.

The following syntax is used to delete the file using os module.

os.remove(“file_path”)

Now let us take an example and delete files using python. We can use the dir keyword to check current files in our directory. Let say we have the following files in our current working directory.

dataframe.csv  mydata.csv  myfile.txt  PythonDeleteFile.py  PythonTutorial  tutor.py

See the example below as well which shows the files in the directory

Python delete file Examples [4 Different Ways]

Now let us delete the file myfile.txt file using the above-mentioned method. See the example below.

import os
os.remove("myfile.txt")

Now let us check the directory by printing all the files using the dir keyword, we get the following file names:

dataframe.csv         PythonDeleteFile.py        tutor.py     mydata.csv         PythonTutorial

Notice that the myfile.txt is no longer in the directory because we deleted that file using python.

If we try to delete a file that does not exist in the directory, we will get an error of FileNotFoundError. See the example below, when we try to delete the file that is not in our directory anymore.

Advertisement
import os
os.remove("myfile.txt")

We already know that we already had deleted the mentioned file, and when we try to run that piece of code, we get the following error.

Python delete file Examples [4 Different Ways]

In a similar way, we can give an absolute file name to delete a file from using the above-mentioned method. See the example below, which deletes the file tutor.py using the absolute pathname.

import os
os.remove("/home/uca/Public/freelanceing/deletefile/tutor.py")

And when we use the dir keyword to list the names of files in the directory, we get the following result.

dataframe.csv      PythonDeleteFile.py       mydata.csv    PythonTutorial

As you can notice the file named tutor.py is no longer in our directory.

 

Check if a file exists before deleting

We already know that, if we try to delete a file that does not exist, we get an error and our program will stop working. 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. In python, we can check to handle this error in two ways. The first one is to use os.path.exist() function to check if the file exists or not and secondly, we can use the python exception handling method to handle the error.

Here we will first use os.path.exist() to make if the file does not exist, we will not get any error. Let us use this method to delete a file that does not exist in our directory and see how we can handle the error. See the python code below:

# importing os
import os

# check if file exists
if os.path.exists("tutor.csv"):

   # delete file
   os.remove("tutor.csv")
else:

   # else print the message
   print("There is no such file!!")

Output:

There is no such file!!

Exception handling is recommended over checking files 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.

Advertisement

Now let us see how we can use the exception handling method to handle the FileNotFoundError. See the example below:

# importing os library
import os

# file name
file_name = 'tutor.csv'
try:

   # removes the file
   os.remove("tutor.csv")
except:

   # print exception message
   print("The file does not exist!")

Output:

The file does not exist!

 

Example-2: Delete the file using os.unlink() method

We can also use os.unlink() method to delete a specified file. This method is only available in UNIX operating system's os module which is similar to the remove method except that it is more familiar in the UNIX environment. The syntax is similar to the remove method. See the simple syntax.

os.unlink("file_name")

Now let us delete the file, mydata.csv from our directory using this method. The code is shown below:

# importing os library
import os

# check if path exist
if os.path.exists("mydata.csv"):
   # python remove file
   os.unlink("mydata.csv")
   print("successfully deleted the file")
else:
   print("error occurred")

Output:

successfully deleted the file

In a similar way, we can use the absolute path to delete files. let us use the absolute path to delete the file named dataframe.csv.  See the following example.

# importing os library
import os

# check if path exist
if os.path.exists("/home/uca/Public/freelanceing/deletefile/dataframe.csv"):

   # python remove file
   os.unlink("/home/uca/Public/freelanceing/deletefile/dataframe.csv")
   print("successfully deleted the file")
else:
   print("error occurred")

Output:

successfully deleted the file

 

Example-3: pathlib module to delete a file in Python

The pathlib module offers classes representing file system paths with semantics appropriate for different operating systems. So, whenever, we need to work with files in multiple environments we can use the pathlib module. The pathlib.path.unlink() method is used to remove the file in the mentioned path.  One of the advantages of this module is that it takes one extra parameter, named missing_ok. If that parameter is set to True, the the pathlib module ignores the FileNotFoundError. otherwise, if the path does not exist, we will get the error.

The simple syntax of deleting file in pathlib module looks like this:

file_name.unlink()

See the example where we use pathlib module to delete a file that exists on our system.

# importing module
import pathlib
import os
# check if file exists
if os.path.exists("myfile.csv"):
   file = pathlib.Path("myfile.csv")

   # Calling the unlink method
   file.unlink()
   print("deleted file successfully")
else:
   print("file not found")

Output:

deleted file successfully

We can use the same method to delete files using the absolute path of files. See the example below which demonstrate deleting of the file using an absolute path.

# importing module
import pathlib
import os

# check if file exists
if os.path.exists("/home/uca/Public/freelanceing/deletefile/myfile.csv"):
   file = pathlib.Path("/home/uca/Public/freelanceing/deletefile/myfile.csv")

   # Calling the unlink method
   file.unlink()
   print("deleted file successfully")
else:
   print("file not found")

Output:

deleted file successfully

 

Example-4: Python delete all files from a directory

Sometimes we may want to delete all the files that exist on a specific directory without deleting the directory itself. Python allows us to do that.  First, we have to get the list of files in a folder using os.listdir(path) method. this method returns a list of names of all the files and folders in a given directory. Then we can iterate over the list of files using for loop and access of the file. Finally, we can use any of the above-given methods to delete files. See the following example which deletes all the files in a specified directory.

# importing os
import os

# store directory path in file
path = '/home/uca/Documents/tutorial'

# for loop to iterate over list of files
for file_name in os.listdir(path):

   # construct full file path
   file = path +"/"+ file_name

   # check if file exist
   if os.path.isfile(file):

       # python delete file
       print('Deleting file:', file)
       os.remove(file)

output:

Deleting file: /home/uca/Documents/tutorial/python.py
Deleting file: /home/uca/Documents/tutorial/filefive.txt
Deleting file: /home/uca/Documents/tutorial/fileone.txt
Deleting file: /home/uca/Documents/tutorial/filefour.txt
Deleting file: /home/uca/Documents/tutorial/filethree.txt
Deleting file: /home/uca/Documents/tutorial/filetwo.txt

In my case, the above-mentioned files were store in the given directory and we have successfully deleted all the files using a for loop to iterate over the name.

 

Summary

Python has a few built-in modules that allow us to delete files and directories. for example os and pathlib module. In this tutorial, we covered various ways to delete files in python using the following modules. We learned how to use os.remove(), os.unlik() and pathlib.path.unlink() to delete the file. We also learned how to handle errors if a file does not exist. Finally, we also learned, how we can delete all files in a specified directory in python. All in all, we covered everything related to the python delete file process.

 

Further Reading

python delete file
python os module to delete
other methods to delete

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment