iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Delete Files

Deleting files lives in the os module; deleting whole folders lives in shutil.

Delete a file

PYTHON
import os
os.remove('hello.txt')

Raises FileNotFoundError if the file isn't there. Guard against that:

PYTHON
if os.path.exists('hello.txt'):
    os.remove('hello.txt')

# Or with pathlib
from pathlib import Path
Path('hello.txt').unlink(missing_ok=True)

Delete an empty folder

PYTHON
os.rmdir('empty_folder')

Errors if the folder has anything in it.

Delete a folder tree

PYTHON
import shutil
shutil.rmtree('build')   # removes build/ and everything inside

The pathlib equivalents

PYTHON
from pathlib import Path

Path('hello.txt').unlink()         # file
Path('empty_folder').rmdir()       # empty folder
# pathlib has no "rmtree" — fall back to shutil

Recursive cleanup with a glob

PYTHON
for log in Path('logs').glob('*.tmp'):
    log.unlink()
Tip: Deleted files don't go to the trash — they're gone. For "send to recycle bin" behaviour, install send2trash from PyPI.

Example

Example
import os
# os.remove('hello.txt')
# os.path.exists('hello.txt') -> False
print('os.remove deletes the file. shutil.rmtree removes a tree.')
Try it Yourself »

Exercise

Module that contains remove() and rmdir().

import os.remove('hello.txt')

Test yourself

Q1. Delete a file with…
Q2. Delete a folder tree with…
Q3. Files deleted by os.remove go to…

Discussion

Loading…