Lesson 97 +10 XP

Delete Files

Delete Files

To delete a file, use the os module's remove().

Delete a file

import os
os.remove("demofile.txt")

Check before deleting

If the file doesn't exist, remove() raises a FileNotFoundError. Check first:

import os
if os.path.exists("demofile.txt"):
    os.remove("demofile.txt")
else:
    print("The file does not exist")

Delete a folder

os.rmdir() removes an empty folder:

import os
os.rmdir("myfolder")

The folder must be empty, or the removal fails.

Remove a folder with contents

For recursive deletion you can use shutil.rmtree(), but it's dangerous, so be careful:

import shutil
shutil.rmtree("myfolder")

os.path

os.path.exists() and os.path.isfile() help you inspect paths before acting.

TL;DR

  • os.remove(file) deletes a file.
  • Check with os.path.exists() first.
  • os.rmdir() removes an empty folder.
  • Deleting is permanent, so guard it carefully.