Home > Article > Backend Development > Detailed example of using python to filter and delete files in a directory
This article mainly introduces you to the relevant information on how to use Python to filter and delete files in a directory. The article introduces it in great detail through sample code. It has certain reference learning value for everyone's study or work. Friends who need it Let’s learn together with the editor below. Hope it helps everyone.
Preface
I recently learned python and feel that it can be used in many places. Packaging, testing, uploading, and movie crawling....and the amount of code is really small. Life is short, I use python. The reason I write this today is because when downloading a movie, you will always find these two files in addition to the video, and even more messy files
formatFiles = [ '.mp4', '.mkv', '.avi', '.rmvb' ] dir = "/Users/cuiyang/Movies/Fmovie/"Step2First create a method to remove all files in the directory
def currentDirFile(dir): fileNames = os.listdir(dir) for fn in fileNames: fullFileName = os.path.join(dir, fn) if not os.path.isdir(fullFileName): delFile(fullFileName) else: currentDirFile(fullFileName)Then Filter the files that need to be deleted. Here, move the files to the trash (mac). If the directory is written incorrectly or deleted accidentally for some reason, then there is no need to do it.
def delFile(filePath): # 分隔后缀名 formatName = os.path.splitext(filePath)[1] if not FilterParameter.formatFiles.__contains__(formatName) and \ filePath.split('/')[-1] != '.DS_Store': # mac下每个文件夹都有个.DS_Store隐藏文件这个不需要动 # print(filePath) shutil.move(filePath, '/Users/cuiyang/.Trash')# 移动到废纸篓Yes, it’s that simple. I believe students who know Python will understand it immediately. Related recommendations:
Detailed explanation of python regular expression re.sub & re.subn
Explanation of python user management system
How to draw a line chart using python
The above is the detailed content of Detailed example of using python to filter and delete files in a directory. For more information, please follow other related articles on the PHP Chinese website!