@(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)