Python Delete Files


In Python, you can delete files using the os module.

First, import it:

import os

🔹 Delete a File

import os

os.remove("sample.txt")

✅ Deletes the file named sample.txt.


🔹 Check if File Exists Before Deleting

import os

if os.path.exists("sample.txt"):
    os.remove("sample.txt")
else:
    print("File does not exist")

✅ Prevents error if the file is missing.


🔹 Delete Empty Folder

import os

os.rmdir("myfolder")

✅ Removes the folder only if it’s empty.


🔹 Delete Non-Empty Folder (Optional)

For non-empty folders, use shutil:

import shutil

shutil.rmtree("myfolder")

⚠️ Use carefully — this deletes everything inside the folder.


🔹 Handle Delete Errors

try:
    os.remove("data.txt")
except FileNotFoundError:
    print("File not found")

✅ Helps avoid crashes when the file doesn’t exist.


🔹 Delete Files with Extension

import os

for file in os.listdir():
    if file.endswith(".log"):
        os.remove(file)

✅ Deletes all .log files in the current directory.


Practice Questions

Q1. Write a Python program to delete a file named demo.txt using os.remove().

Q2. Write a Python program to delete a file only if it exists, using os.path.exists().

Q3. Write a Python program to delete a folder named temp only if it’s empty, using os.rmdir().

Q4. Write a Python program to use try/except to safely delete a file that might not exist.

Q5. Write a Python program to use a loop to delete all .bak files from a directory.

Q6. Write a Python program to use shutil.rmtree() to remove a folder with all its contents.

Q7. Write a Python program to define a function that deletes a file if it is found, and returns success or failure.

Q8. Write a Python program to remove a folder and handle permission errors using a try/except block.

Q9. Write a Python program to prompt the user to enter a file name and delete it if it exists.

Q10. Write a Python program to log a message when a file is deleted successfully (e.g., print "File deleted.").


Go Back Top