@(cookbook)[python, dir]
问题
python遍历和删除指定目录下所有的pyc文件。但是在指定目录中有node_modules子目录,改目录文件巨多,层级巨深。因此还要排除此子目录。
解决方案
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = 'delete *.pyc file'
__author__ = 'gasxia'
__mtime__ = '9/21/2016'
"""
import fnmatch
from os import walk, path, remove, listdir
import sys
if len(sys.argv) >= 3:
EXT = sys.argv[2]
DEL_DIR = sys.argv[1]
elif len(sys.argv) >= 2:
EXT = 'pyc'
DEL_DIR = sys.argv[1]
else:
EXT = 'pyc'
DEL_DIR = r'F:\jinrunsen\Projects\notus'
if not path.exists(DEL_DIR):
print('error: DEL_DIR not found!!!')
exit()
print('DEL_DIR: ', DEL_DIR, '\ndelete file extension: ', EXT)
print('deleted files:\n')
def del_pyc(DEL_DIR):
# highpath: 最高级目录,排除掉'node_modules'
for highpath in listdir(DEL_DIR):
# 去除顶层目录中的pyc文件
if os.path.isfile(highpath):
if fnmatch.fnmatch(highpath, '*.' + EXT): # unix shell风格匹配方式
# if filename.endswith('.pyc'):
print(filename)
remove(path.join(filepath, filename))
print highpath
if path.basename(highpath) == 'node_modules':
continue
# lowpath: 其余的子目录
lowpath = path.join(DEL_DIR, highpath)
for filepath, _, filename_list in walk(lowpath):
for filename in filename_list:
if fnmatch.fnmatch(filename, '*.' + EXT): # unix shell风格匹配方式
# if filename.endswith('.pyc'):
print(filename)
remove(path.join(filepath, filename))
if __name__ == '__main__':
del_pyc(DEL_DIR)
讨论