45. How do I delete a file using Python?

Source: Internet
Author: User

To use Python to delete files from Windows, you need an OS module ! Then take a look at how the OS module deletes files!

The specific implementation method is as follows!

Os.remove (PATH)

Delete the file path. If path is a directory , throw a oserror error. If you want to delete a directory, use RmDir ().

Remove () has the same function as unlink ()
In a Windows system, an exception is thrown when you delete a file that is in use. In Unix, the records in the catalog table are deleted, but the storage of the files is still there.

 import   osmy_file  = "  d:/text.txt   " #   file path  if  Os.path.exists (my_file): #   If file exists  #   to delete files, use the following two methods.  os.remove (my_file) #   delete  #  os.unlink (my_file)   else  :  print  ("  no such file:%s   "%my_file )

os.removedirs (path)
Removes 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 Baz directory and then remove Bar and foo, if they are empty, then subdirectories cannot be deleted successfully and will throw OSError exception

os.rmdir (path)
Delete directory path, requires path to be an empty directory, otherwise throws OSError error

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 2:
The code is as follows:

Import Shutilshutil.rmtree ()

45. How do I delete a file using Python?

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.