Python File Handling

Python Delete Files

Deleting files

Python Delete Files

To delete a file, you must import the OS module, and run its os.remove() function.

Delete a File

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

Check if File Exists

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

Delete Folder

import os
os.rmdir("myfolder")

Python File Handling — Knowledge Check

Check your understanding of this section. Results are not saved—refresh the page to start over.

1. Which mode opens a file for reading only?
2. Why use 'with open(...) as f'?
3. What does f.read() return for a text file opened in text mode?
4. To add new content without erasing the file, use:
5. How do you remove a file in Python?