Python implements methods for deleting files and directories

Source: Internet
Author: User

os.remove (path) to delete the file path. If path is a directory, throw a oserror error. If you want to delete a directory, use rmdir (). Os.rmdir () can only delete empty directories

Remove () is the same as unlink () in a Windows system, deleting a file that is in use will throw an exception. In Unix, the records in the catalog table are deleted, but the storage of the files is still there.

os.removedirs (path) to delete the directory recursively. Similar to RmDir (), if a subdirectory is successfully deleted, Removedirs () will delete the parent directory, but the subdirectory is not successfully deleted and an error will be thrown.

For example, Os.removedirs ("Foo/bar/baz") will first delete the "Foo/bar/ba" directory, and then delete Foo/bar and foo, if they are empty, such as the fruit directory cannot be deleted successfully, will throw OSError exception

os.rmdir (path) removes directory path, requires path to be an empty directory, otherwise throws OSError error recursively deletes directories and files (like DOS command DeleteTree):

Method One:

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) )

Method Two:

Import Shutilshutil.rmtree ()

Method Three:

__import__ ('shutil'). Rmtree ()

Python implements methods for deleting files and directories

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.