Python implements methods to delete files and directories

  • 2020-04-02 14:22:42
  • OfStack

This article illustrates a python implementation for deleting files and directories. Share with you for your reference. The specific implementation method is as follows:

OS. Remove (path)
Delete the file path. If path is a directory, throw an OSError. If you want to delete a directory, use rmdir().

Remove () The same functionality as unlink()
In Windows, deleting a file in use throws an exception. In Unix, records in directory tables are deleted, but the storage of files remains.

OS. Removedirs (path)
Recursively deletes directories. Similar to rmdir(), if the subdirectory is successfully removed, removedirs() will remove the parent directory; But the subdirectory was not successfully deleted and an error is thrown.

For example, os.removedirs(" foo/bar/baz ") will first remove the "foo/bar/ba" directory, and then foo/bar and foo, if they are empty
If the subdirectory cannot be successfully deleted, an OSError exception is thrown

OS. Rmdir (path)
Remove the directory path, which must be an empty directory, otherwise an OSError is thrown
 
Recursively delete directories and files (similar to the DOS command DeleteTree) :

import os
for root, dirs, 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:

import shutil
shutil.rmtree()

One line done:
__import__('shutil').rmtree()

I hope this article has helped you with your Python programming.


Related articles: