Computer Science Atlas
Code Review

Python 3 Examples: Delete (Remove) a File

February 25, 2021
 

This article shows how to delete (remove) a single file in Python. To remove an entire directory, see Python 3 Examples: Remove Directory Recursively (Like rm -r).

Using pathlib (Python 3.4 and up)

Remove Existing File (Like rm)

To remove the file /tmp/myfile.txt on Python 3.4 or higher, you can use the built-in pathlib library:

Copy
from pathlib import Path

Path( '/tmp/myfile.txt' ).unlink()
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.

Ignore If File Does Not Exist (Like rm -f)

Python 3.8 and up

On Python 3.8 and higher, you can suppress the FileNotFoundError by passing in the missing_ok=True argument:

Copy
from pathlib import Path

Path( '/tmp/myfile.txt' ).unlink( missing_ok=True )
1
2
3
from pathlib import Path

Path( '/tmp/myfile.txt' ).unlink( missing_ok=True )

All Python 3 Versions

On all Python 3 versions, you can also just check beforehand if the file exists:

Copy
from pathlib import Path

myfile = Path( '/tmp/myfile.txt' )
if myfile.exists():
    myfile.unlink()
1
2
3
4
5
from pathlib import Path

myfile = Path( '/tmp/myfile.txt' )
if myfile.exists():
    myfile.unlink()

Using os

Remove Existing File (Like rm)

To remove the file /tmp/myfile.txt on any version of Python 3, you can also use the built-in os library:

Copy
import os

os.unlink( '/tmp/myfile.txt' )
1
2
3
import os

os.unlink( '/tmp/myfile.txt' )

Ignore If File Does Not Exist (Like rm -f)

Copy
import os

myfile = '/tmp/myfile.txt'
if os.path.exists( myfile ):
    os.unlink( myfile )
1
2
3
4
5
import os

myfile = '/tmp/myfile.txt'
if os.path.exists( myfile ):
    os.unlink( myfile )

References