当然使用 shell 一行就能解决!
不过 需求使用 python 所以
#coding=UTF-8
import os
import re
import sys
#递归遍历指定的目录
#param:
# array -- 递归寄存数组
# level -- 递归的层数,用这个参数来控制打印的缩进
# path == 遍历起始绝对路径
#return:
# array 返回 {"type":文件类型(f|d),"path":物理文件路径name":文件名"exp":文件扩展名,称,"level":深度}
# 参考:http://www.javaeye.com/topic/116670
_comms = {'-s':'策略','-p':'查找路径','-c':'替换命令'}
_mapSub = ("path", "name", "exp","type","level")
_mapSub_re = {}
for tmp in _mapSub:
_mapSub_re[tmp] = re.compile("\$\s*\{\s*"+tmp+"\s*\}")
def listAll(array, level, path):
for file in os.listdir(path):
if os.path.isfile(path + "\\" + file):
fe = file.split(".")
path = re.sub("\\\\", "/", path)
if len(fe)>=2:
array.append({_mapSub[3]:"f", _mapSub[0]:path, _mapSub[1]:".".join(fe[0:-1]), _mapSub[2]:fe[-1], _mapSub[4]:str(level + 1)})
else:
array.append({_mapSub[3]:"d", _mapSub[0]:path, _mapSub[1]:file, _mapSub[2]:"", _mapSub[4]:str(level + 1)})
else:
array.append({_mapSub[3]:"d", _mapSub[0]:path, _mapSub[1]:file, _mapSub[2]:"", _mapSub[4]:str(level + 1)})
listAll(array, level + 1, path + "\\" + file)
def _main():
if len(sys.argv)==1:
print "请输入参数 -s 策略 -p 查找路径 -c 替换命令 "
print ' 如 :listdir.py -p . -s findMp3 -c "ls ${path}/${name}.${exp}" '
exit(0)
argvs = sys.argv[1:]
#argvs = '-s&findMp3&-p&.&-c&"ls ${path}/${name}.${exp}"'.split("&")
for tc in _comms.keys():
for i in range(len(argvs)):
if(argvs[i]==tc):
_comms[tc]=argvs[i+1]
#
reLGPath = re.compile("^\s*\\.")
if reLGPath.match(_comms['-p']):
_comms['-p'] = os.path.abspath(_comms['-p'])
_comms['-p'] = re.sub("\\\\","/",_comms['-p'])
script = _comms['-s']+'()'
for fmap in eval(script):
tcomm = _comms['-c']
for tk in _mapSub_re.keys():
tcomm = _mapSub_re[tk].sub(fmap[tk]+"", tcomm+"")
#print tcomm
os.system(tcomm)
#***********************************************************************************************
# 策略 添加
#***********************************************************************************************
#查找 mp3 策略
def findMp3():
array = []
mp3Array = []
listAll(array, 0, _comms['-p'])
p = re.compile("[mM][pP]3")
for tmap in array:
# 类型 文件 扩展名 mp3
if tmap[_mapSub[3]] == "f" and p.match(tmap[_mapSub[2]]) :
mp3Array.append(tmap)
return mp3Array
#***********************************************************************************************
# 测试代码 listdir.py -p . -s findMp3 -c "ls ${path}/${name}.${exp}"
# 可替换 ${path} ${name} ${exp} ${level} ${type}
#***********************************************************************************************
_main()
整理 www.blogjava.net/Good-Game