How can I delete a file or folder in Python?
Published on Aug. 22, 2023, 12:16 p.m.
To delete a file or folder in Python, you can use the functions provided in the os
and shutil
modules.
For deleting a file, you can use the os.remove()
or os.unlink()
function. Here is an example:
import os
if os.path.exists("file.txt"):
os.remove("file.txt")
For deleting an empty directory, you can use the os.rmdir()
function. Here is an example:
import os
if os.path.exists("my_folder"):
os.rmdir("my_folder")
If you want to delete a directory and all its contents (whether it is empty or not), you can use the shutil.rmtree()
function. Here is an example:
import shutil
if os.path.exists("my_folder"):
shutil.rmtree("my_folder")
Note that when using rmtree()
, you should make sure that you want to delete the entire directory and all its contents, since the deletion is permanent and cannot be undone.
Also, before attempting to delete a file or folder, make sure that they exist by using the os.path.exists()
function. This helps to prevent errors if you try to delete a file or folder that does not exist.