Python script for file cleanup,

Source: Internet
Author: User

Python script for file cleanup,

Since I first wrote a blog on cnblog, I found that the webpage version could not be directly pasted with images. With the help of a mac computer, the shortcut key saved the images on the table.

In addition, a lot of things are downloaded.

I wrote a small script and put it in the local bin folder, which can reduce the burden on the mouse.

The Code is as follows:

#!/Users/alex/anaconda/bin/pythonimport os,re,shutildef delMess(path,reStr,flag=0):    os.chdir(path)    fileList=os.listdir(path)    if flag==0:        for filename in fileList:            m=re.search(reStr, filename)            if m:                os.remove(m.group())    else:        for filename in fileList:            m=re.search(reStr, filename)            if not m:                try:                    os.remove(filename)                except OSError:                    shutil.rmtree(filename)                                                    delMess("/Users/alex/Desktop", ".*\.png")delMess("/Users/alex/Downloads",".*\.iso",1)    

The basic function is simple. The default flag is 0, that is, the png image on the desktop is cleared.

Flag = 1 is used to delete all files of different categories, including folders.

Tricky is used to delete folders. Due to the time limit, the OS module is not discussed in detail.

OsError is thrown if you delete a file to a folder.

Rmdir cannot be used either, because non-empty folders cannot be deleted. If you delete a non-empty folder, an osError exception is thrown.

So the code is simplified to remove the file. If there is an exception, use rmtree.

 

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.