This article describes the Python implementation method for deleting files and directories. Share to everyone for your reference. The implementation methods are as follows:
Os.remove (PATH)
deletes the file path. If path is a directory, throw a oserror error. If you want to delete a directory, use RmDir ().
The remove () function is the same as unlink ()
In a Windows system, deleting a file that is in use throws an exception. In Unix, records in a catalog table are deleted, but the files are stored.
Os.removedirs (PATH)
deletes a directory recursively. Similar to RmDir (), if a subdirectory is successfully deleted, Removedirs () deletes the parent directory, but the subdirectory is not successfully deleted, and an error is thrown.
For example, Os.removedirs ("Foo/bar/baz") will first delete the "Foo/bar/ba" directory and then remove Foo/bar and foo if they are empty
If the subdirectory cannot be successfully deleted, the OSError exception is thrown
Os.rmdir (PATH)
Delete directory path, request path must be an empty directory, or throw OSError error
Recursively delete directories and files (similar to DOS command DeleteTree):
Copy Code code as follows:
Import OS
For Root, dirs, the files in Os.walk (top, Topdown=false):
For name in Files:
Os.remove (Os.path.join (root, name))
For name in dirs:
Os.rmdir (Os.path.join (root, name))
Method 2:
Copy Code code as follows:
Import Shutil
Shutil.rmtree ()
One line to fix:
Copy Code code as follows:
__import__ (' Shutil '). Rmtree ()
I hope this article will help you with your Python programming.