1. (path)
Delete directory path. path must be an empty directory, otherwise an OSError exception will be thrown.
import os ('./test') # testIt's an empty folder
2. (path)
Recursively delete the directory. Each level of directory is required to be empty in order to recursively delete all directories. The parent directory is deleted only if the subdirectory is successfully deleted; if the subdirectory is not successfully deleted, an OSError exception will be thrown.
import os #test2 is a subfolder of test. If test2 is not empty, an exception is thrown; if test2 is empty and test is not empty, test2 is deleted successfully, test will not be deleted, but no exception is reported('./test/test2)
III. (path)
Delete regardless of whether the directory path is empty or not.
import shutil ('./test') # deletetestAll files in the folder、Folders
4. Delete files
Pathlib
from pathlib import Path # Define the file path to deletefile_to_delete = Path('/home/python/test/') try: # Check if the file exists if file_to_delete.exists() and file_to_delete.is_file(): # Delete the file file_to_delete.unlink() print(f"File {file_to_delete} has been deleted.") else: print(f"File {file_to_delete} does not exist or is not a file.") except Exception as e: print(f"An error occurred: {e}")
os
import os # Define the file path to deletefile_to_delete = '/home/python/test/' try: # Check if the file exists if (file_to_delete) and (file_to_delete): # Delete the file (file_to_delete) print(f"File {file_to_delete} has been deleted.") else: print(f"File {file_to_delete} does not exist or is not a file.") except Exception as e: print(f"An error occurred: {e}")
This is the end of this article about three methods of deleting directories in Python. For more related contents of deleting directories in Python, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!