How to delete file in python
How to delete file in python
Python delete file Examples [4 Different Ways]
Table of Contents
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.
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
Using this library we can create new files and directories. See the following syntax for creating new empty directory using os module.
Now let us create an empty directory using the os module. See the following example:
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:
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.
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.
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.
See the example below as well which shows the files in the directory
Now let us delete the file myfile.txt file using the above-mentioned method. See the example below.
Now let us check the directory by printing all the files using the dir keyword, we get the following file names:
Notice that the myfile.txt is no longer in the directory because we deleted that file using python.
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.
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.
And when we use the dir keyword to list the names of files in the directory, we get the following result.
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:
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.
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.
Now let us delete the file, mydata.csv from our directory using this method. The code is shown below:
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.
Example-3: pathlib module to delete a file in Python
The simple syntax of deleting file in pathlib module looks like this:
See the example where we use pathlib module to delete a file that exists on our system.
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.
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.
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
Further Reading
Related Posts
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.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Python Delete File
Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:
Example
Remove the file «demofile.txt»:
Check if File exist:
To avoid getting an error, you might want to check if the file exists before you try to delete it:
Example
Check if file exists, then delete it:
Delete Folder
To delete an entire folder, use the os.rmdir() method:
Example
Remove the folder «myfolder»:
Note: You can only remove empty folders.
We just launched
W3Schools videos
COLOR PICKER
Get certified
by completing
a course today!
CODE GAME
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Web Courses
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
How to Delete File in Python?
Learn about how to delete file in python.
Overview
Python programmers use files for a variety of purposes. One of the most crucial functions you need to know when working with files is how to delete a file. Take, for example, a programme that analyses the performance of the S&P 500 index and saves the results in a file. You may want to delete any existing analysis files to make room for the new file. The os.remove() method in Python can be used to remove files, and the os.rmdir() method can be used to delete an empty folder. The shutil.rmtree() method can be used to delete a folder along with all of its files.
Scope
Introduction
Sometimes after you’ve worked with your file and do not require it anymore, you can delete it using python. Say, in an extensive program, you needed to create files to store data but did not require them after the program’s execution. It’s a good idea to delete those files, and we’ll see how to do that using python in this article.
How to Delete Files Using Python?
Removing the files or a single file from a particular directory when it is no longer required is the basic concept of deleting a file. Now to remove a file, you have three methods. Using one of the modules:
1. Using the os module in python
The os module allows you to use the operating system-dependent functionalities.
To use the os module to delete a file, we first need to import it, then use the remove() function provided by the module to delete the file. It takes the file path as a parameter.
You can not just delete a file but also a directory using the os module.
To delete a file:
On the other hand, if you wish to delete or clear a directory, you can do it with the help of the rmdir() function of the os module. Note that the directory must be empty for this to work.
If the directory to delete is in the same directory as the python program, then you need not provide a full path. A relative path will work. Else, a path can be written as the parameter of the rmdir function.
2. Using the shutil module in python:
The shutil module is a high-level file operation module. You can perform functions like copying and removal on files and collections of files.
Now here is the place of path you can provide the path to your directory that you wish to remove.
You cannot delete a single file with the shutil.rmtree() function.
3. Using the Pathlib Module in Python
If you’re working with a python version 3.4+, then the pathlib module is beneficial for deleting/removing files.
The pathlib module has many similarities with the os module, two of them being the remove and rmdir methods.
Now, when working with this module, you must first create a Path object. When an instance of the Path class is created, a WindowsPath or PosixPath will be returned according to the machine you’re working on. For Windows OS, a WindowsPath object will be returned, and for non-windows OS like linux, PosixPath will be returned.
Then, the next step is to use the unlink() function. The unlink() function is used to remove the file or the symbolic link. If you wish to delete a directory, you must use the rmdir() function instead.
The same way, if you want to delete a directory:
But again, the rmdir() function only allows you to delete empty directories.
We can summarise it all with the following table:
Deleting a single file? | Os |
---|---|
Pathlib | |
Deleting Empty Directories? | Os |
Pathlib | |
Deleting non-empty Directories? | Shutil |
Conclusion
After learning about Deleting Files in Python, here are some key points that will help you:
How do I delete a file or folder in Python?
How do I delete a file or folder?
16 Answers 16
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
os.rmdir() removes an empty directory.
shutil.rmtree() deletes a directory and all its contents.
Path objects from the Python 3.4+ pathlib module also expose these instance methods:
pathlib.Path.unlink() removes a file or symbolic link.
pathlib.Path.rmdir() removes an empty directory.
Python syntax to delete a file
pathlib Library for Python version >= 3.4
Path.unlink(missing_ok=False)
Unlink method used to remove the file or the symbolik link.
Best practice
EXAMPLE for os.path.isfile
Exception Handling
RESPECTIVE OUTPUT
Python syntax to delete a folder
Example for shutil.rmtree()
(See complete documentation on shutil) and/or
(Complete documentation on os.)
Here is a robust function that uses both os.remove and shutil.rmtree :
To remove a file there is the unlink method:
Or the rmdir method to remove an empty folder:
How do I delete a file or folder in Python?
For Python 3, to remove the file and directory individually, use the unlink and rmdir Path object methods respectively:
For removing individual files and directories in Python 2, see the section so labeled below.
Demonstration
New in Python 3.4 is the Path object.
Let’s use one to create a directory and file to demonstrate usage. Note that we use the / to join the parts of the path, this works around issues between operating systems and issues from using backslashes on Windows (where you’d need to either double up your backslashes like \\ or use raw strings, like r»foo\bar» ):
Now let’s delete them. First the file:
Then just iterate over the glob pattern:
Now, demonstrating removing the directory:
What if we want to remove a directory and everything in it? For this use-case, use shutil.rmtree
Let’s recreate our directory and file:
and note that rmdir fails unless it’s empty, which is why rmtree is so convenient:
Now, import rmtree and pass the directory to the funtion:
and we can see the whole thing has been removed:
Python 2
If you’re on Python 2, there’s a backport of the pathlib module called pathlib2, which can be installed with pip:
And then you can alias the library to pathlib
Or just directly import the Path object (as demonstrated here):
How To Delete Files in Python
Introduction
In our Python file handling Tutorial, we learned how to manipulate files from within Python. In this tutorial, we’ll learn how to delete files in Python.
We know how to read from and write to a file in Python. Let’s learn the delete operation in Python today.
Suppose after successfully creating a file, we perform some operations on it like reading and writing. As soon as we are done using the file for analyzing different sets of data, maybe in some cases, we don’t need it in the future. At this point how do we delete the file? In this tutorial, we are going to learn that.
Methods to Delete Files in Python
Let us take a look at the different methods using which we can delete files in Python.
1. Using the os module
The os module in Python provides some easy to use methods using which we can delete or remove a file as well as an empty directory. Look at the below-given code carefully:
Here we have used an if-else statement to avoid the exception that may arise if the file directory doesn’t exist. The method isfile() checks the existence of the file with filename- ‘new_file.txt’.
Note: The directory must be an empty one. If it contains any content, the method we return an OSerror.
2. Using the shutil module
The shutil is yet another method to delete files in Python that makes it easy for a user to delete a file or its complete directory(including all its contents).
rmtree() is a method under the shutil module which removes a directory and its contents in a recursive manner. Let us see how to use it:
For the above-mentioned code, the directory ‘/test/’ is removed. And most importantly, all the contents inside the directory are also deleted.
3. Using the pathlib module
pathlib is a built-in python module available for Python 3.4+. We can remove a file or an empty directory using this pre-defined module.
Let’s go for an example:
In the above example, the path() method is used to retrieve the file path whereas, the unlink() method is used to unlink or remove the file for the specified path.
The unlink() method works for files. If a directory is specified, an OSError is raised. To remove a directory, we can resort to one of the previously discussed methods.