Delete a file or folder using Python

Source: Internet
Author: User

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

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.