Python implements the method of deleting files and directories _python

Source: Internet
Author: User
Tags parent directory

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.

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.