Python Delete Files

Python Delete Files

To delete a file in Python, you cannot use a method from the standard file object. Instead, you must import the os module, and use its built-in os.remove() function.

The os module provides a portable way of using operating system dependent functionality.


1. Deleting a File

To remove a file, pass the filename (and path, if it's not in the current directory) to os.remove().

import os
# Delete the file named "demofile.txt"
os.remove("demofile.txt")

2. Check if File Exist Before Deleting

To avoid getting an error (like a FileNotFoundError), you might want to check if the file exists before trying to delete it. You can do this using os.path.exists().

Safe Deletion Example

import os

file_to_delete = "demofile.txt"

if os.path.exists(file_to_delete): os.remove(file_to_delete) print("The file has been deleted.") else: print("The file does not exist!")


3. Delete a Folder

To delete an entire folder, use the os.rmdir() method.

Note: You can only remove empty folders using os.rmdir(). If the folder contains files, it will throw an error.

import os
# Delete the folder named "myfolder"
os.rmdir("myfolder")

Exercise

?

Which module must you import to delete files and folders in Python?