Computer Science Atlas
Snippets

Python 3: Delete (Remove) a File

February 25, 2021|Updated January 20, 2022
 
Table of Contents

This article shows how to delete (remove) a single file in Python. To remove an entire directory, see [](/python-remove-directory/).

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:

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:

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 )

Python 3.4 and up

On Python 3.4 and higher, you can also just check beforehand if the file exists:

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:

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)

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