當(dāng)然使用 shell 一行就能解決!
不過 需求使用 python 所以
#coding=UTF-8
import os
import re
import sys
#遞歸遍歷指定的目錄
#param:
# array -- 遞歸寄存數(shù)組
# level -- 遞歸的層數(shù),用這個參數(shù)來控制打印的縮進(jìn)
# path == 遍歷起始絕對路徑
#return:
# array 返回 {"type":文件類型(f|d),"path":物理文件路徑name":文件名"exp":文件擴(kuò)展名,稱,"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 "請輸入?yún)?shù) -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:
# 類型 文件 擴(kuò)展名 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()
整理 m.tkk7.com/Good-Game