Delete a file in Python
This post will discuss how to delete a file in Python.
1. Using os.remove() function
The standard solution to delete a file in Python is using the os.remove() function. It accepts a path that should be a file; otherwise, an exception is raised.
|
1 2 3 4 5 |
import os path = '/path/to/file/filename.ext' os.remove(path) |
To handle the case when the specified path is a directory, you should either:
1. Check for the existence of the file before deleting it:
|
1 2 3 4 5 6 7 8 |
import os path = '/path/to/file/filename.ext' if os.path.isfile(path): os.remove(path) else: print('Path is not a file') |
2. Catch exception with try-except:
|
1 2 3 4 5 6 7 8 |
import os path = '/path/to/file/filename.ext' try: os.remove(path) except: print('Path is not a file') |
2. Using os.unlink() function
Alternatively, you can use the os.unlink() function to delete a file which is semantically identical to os.remove() function.
|
1 2 3 4 5 6 7 8 |
import os path = '/path/to/file/filename.ext' if os.path.isfile(path): os.unlink(path) else: print('Path is not a file') |
3. Using pathlib.Path.unlink() function
Starting with Python 3.4, consider using the Path.unlink() function from the pathlib module to remove a file or symbolic link.
|
1 2 3 4 5 |
import pathlib path = pathlib.Path('/path/to/file/filename.ext') path.unlink() |
That’s all about deleting a file in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)