This article shows how to delete (remove) a single file in Python. To remove an entire directory, see [](/python-remove-directory/).
pathlib (Python 3.4 and up)rm)To remove the file /tmp/myfile.txt on Python 3.4 or higher, you can use the built-in pathlib library:
1 2 3 | from pathlib import Path Path( '/tmp/myfile.txt' ).unlink() |
This call will raise a FileNotFoundError if /tmp/myfile.txt does not exist.
rm -f)On Python 3.8 and higher, you can suppress the FileNotFoundError by passing in the missing_ok=True argument:
1 2 3 | from pathlib import Path Path( '/tmp/myfile.txt' ).unlink( missing_ok=True ) |
On Python 3.4 and higher, you can also just check beforehand if the file exists:
1 2 3 4 5 | from pathlib import Path myfile = Path( '/tmp/myfile.txt' ) if myfile.exists(): myfile.unlink() |
osrm)To remove the file /tmp/myfile.txt on any version of Python 3, you can also use the built-in os library:
1 2 3 | import os os.unlink( '/tmp/myfile.txt' ) |
rm -f)1 2 3 4 5 | import os myfile = '/tmp/myfile.txt' if os.path.exists( myfile ): os.unlink( myfile ) |