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.
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")
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().
import osfile_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!")
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")
Which module must you import to delete files and folders in Python?