Python delete file sample share _python

Source: Internet
Author: User

deleting files

Copy Code code as follows:

Os.remove (filename) # filename: "File name to delete"

Possible causes of an exception:

(1) filename does not exist
(2) The filename file, no permission to operate or read-only.

Delete all files and subfolders under the folder:

Copy Code code as follows:

Import OS
def delete_file_folder (SRC):
"' Delete files and folders '"
If Os.path.isfile (SRC):
Try
Os.remove (SRC)
Except
Pass
Elif Os.path.isdir (SRC):
For item in Os.listdir (SRC):
Itemsrc=os.path.join (Src,item)
Delete_file_folder (ITEMSRC)
Try
Os.rmdir (SRC)
Except
Pass
If __name__== ' __main__ ':
Dirname=r ' G:\windows '
Print Delete_file_folder (dirname)

Or you can use the Rmtree function of the Shutil module, or cascade the deletion

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.