Python Delete
In Python, we can use any of the three methods to delete a file or folder that is no longer needed:
- os module
- pathlib module
- shutil module
os module
With the help of the os module, we can check if a file exists in the directory, delete a file and delete a directory. To use the os module, we have to import the os module.
Check if file exists
To check whether the file exists in the directory or not, we have to use os.path.isfile(file path).
When file exists.
import os
file_name = "Test File.txt"
if os.path.isfile(file_name):
print("File is available.")
else:
print("File does not exist.")
When file does not exists.
import os
file_name = "Test File_2.txt"
if os.path.isfile(file_name):
print("File is available.")
else:
print("File does not exist.")
Deleting a File
To delete the file, we use os.remove(filepath/filename).
import os
file_name = "Test File.txt"
if os.path.isfile(file_name):
os.remove(file_name)
print("File deleted successfully.")
else:
print("File does not exist.")
Delete a Directory
To delete a directory, we use os.rmdir(directory path).
Note:- We can delete only empty directory using os.rmdir.
import os
os.rmdir("Empty Folder")
pathlib module
The pathlib module is available for python version 3.4+.
Delete a File
First we create the Path object and then use the unlink() function.
import pathlib
file = pathlib.Path("Test File.txt")
file.unlink()
Delete a Directory
Again, we have to first create the path object and then use the rmdir() function.
Note: With rmdir(), we can only delete the empty directories.
import pathlib
folder = pathlib.Path("Empty Folder")
folder.rmdir()
shutil module
Delete a File
The shutil cannot be used to delete a file.
Delete a Directory
With the shutil module we can remove a directory using the rmtree() method.
Note: With this, we can remove non-empty directory as well.
import shutil
shutil.rmtree("non-empty folder")