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.