To delete a file in Python, you can use the os
module's remove()
function. This function takes the name of the file as an argument and removes it from the file system.
For example:
import os # Delete the file "test.txt" os.remove("test.txt")
If the file does not exist, the remove()
function will raise a FileNotFoundError
exception. You can use a try
-except
block to handle this exception:
import os try: # Delete the file "test.txt" os.remove("test.txt") except FileNotFoundError: print("File not found")
Alternatively, you can use the os.path
module's exists()
function to check if the file exists before calling os.remove()
:
import os if os.path.exists("test.txt"): # Delete the file "test.txt" os.remove("test.txt") else: print("File not found")
You can also use the shutil
module's rmtree()
function to delete a directory and all of its contents, including any subdirectories and files. This function takes the name of the directory as an argument.
For example:
import shutil # Delete the directory "test" and all of its contents shutil.rmtree("test")
Like the os.remove()
function, shutil.rmtree()
will raise a FileNotFoundError
exception if the directory does not exist. You can use a try
-except
block to handle this exception, or use the os.path.exists()
function to check if the directory exists before calling shutil.rmtree()
.