Using Python to delete a file or folder requires the use of an OS module.
Import OS
Os.remove (path) # Path is the path to the file, and if the path is a folder, it throws a OSError error, which needs to be removed with rmdir ()
Os.rmdir (path) # path is a folder path, note that the folder needs time and space to be deleted
Os.unlink (' f:\ new text document '. txt ') # unlink function and remove is the same as removing a file, but deleting a file that is being used will cause an error.
import Ospath = ' F :/new text document. txt " # file path if os.path.exists (path): # # delete files and use the following two methods. os.remove (path) # os.unlink (Path)
else : print ( no such file:%s %my_file) # The return file does not exist
Import OS
Os.removedirs (PATH) # recursively deletes the directory. If the subdirectory is successfully deleted, the parent directory will be successfully deleted, and the subdirectory will not be deleted successfully, throwing an exception.
Import OS for in Os.walk (top, topdown=False): for in files: os.remove ( Os.path.join (root, name)) for in dirs: Os.rmdir (Os.path.join (Root, name ))
A different approach
Import Shutilshutil.rmtree ()
Delete a file or folder using Python