Python script to clean up files

Source: Internet
Author: User

Since the beginning of the Cnblog blog, found that the Web version can not directly paste pictures, plus the use of Mac computers, shortcut keys directly to the picture on the table.

Plus a whole bunch of stuff to download.

Just write a small script, and then put in the local bin folder, finally can reduce some of the mouse burden.

The code is as follows:

#!/users/alex/anaconda/bin/pythonImportOs,re,shutildefDelmess (path,restr,flag=0): Os.chdir (path) fileList=os.listdir (path)ifflag==0: forFileNameinchfilelist:m=re.search (restr, filename)ifM:os.remove (M.group ())Else:         forFileNameinchfilelist:m=re.search (restr, filename)if  notm:Try: os.remove (filename)exceptOSError:shutil.rmtree (filename) delmess ("/users/alex/desktop",". *\.png") delmess ("/users/alex/downloads",". *\.iso", 1)    

Basic ability is simple, the default flag is 0, that is, to clean up the PNG image on the desktop

The function of flag=1 is to delete all files that are not of a certain category, including folders

The place to compare tricky is to delete the folder, because the time limit does not delve into the OS module

Found deleting files if deleted to folder will throw OSError

RmDir cannot be used because a non-empty folder cannot be deleted, and a OSError exception will be thrown if non-null is omitted.

So the code is simplified into a remove file, and if there is an exception, use Rmtree.

Python script to clean up files

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.