删除特定类型的文件

Github上有些项目的源码中包含了.pyc文件,这些字节编译的文件在运行时可以提高速度,但我主要用于阅读,不要他们。于是写了几行python代码来完成删除的功能,当然这段代码也很容易应用到其他文件类型。

 1 import os
 2 def del_file(dirpath, postfix):
 3     '''
 4     删除包含指定后缀名的文件
 5     包括子目录中的文件
 6     '''
 7     os.chdir(dirpath)
 8     for root, dirs, files in os.walk(os.getcwd()):
 9         for file in files:
10             shortname, extension = os.path.splitext(file)
11             if extension == postfix:
12                 os.remove(os.path.realpath(file))
13               # print('delete %s' % file)
14             
15     print('Delete all files with %s' % postfix)
16 
17 
18 if __name__ == "__main__":
19     del_file('D:/Project/myblog/', '.pyc')

os.walk非常有用,可以自动搜索子目录中文件,返回值包括root, dirs和files。

PS:一开始我使用glob模块,但是其没有自动搜索子目录的方法,但是glob模块有些很好玩的方法,可以查看目录下特定的文件,例如glob.glob('examples/*.xml')显示emamples目录下所有xml型文件。

原文地址:https://www.cnblogs.com/leonfocus/p/filedeletor.html