import os
# your functions
def xc(contents): ....
def x(contents): ....
# store function references in a dict to dispatch, this is a common python idiom
funcMap = {'.xc': xc, '.x':x}
for dirpath, dirnames, filenames in os.walk(someDir):
# use os.walk to iterate someDir's contents recursively. No
# need to implement recursion yourself if stdlib does it for you
for f in filenames:
ext = os.path.splitext(f)[1]
try:
function = funcMap[ext]
except KeyError:
# no function to process files with extension 'ext', ignore it
pass
else:
abspath = os.path.join(dirpath, f)
with open(abspath) as f:
function(f.read())
import os
for dirpath, dnames, fnames in os.walk("./"):
for f in fnames:
if f.endswith(".x"):
x(os.path.join(dirpath, f))
elif f.endswith(".xc"):
xc(os.path.join(dirpath,f))
import os
def process_directory(dirName):
"""Recursively process all .xc and .x files in a parent directory and its
subdirectories"""
dirName = os.path.abspath(dirName)
for f in os.listdir(dirName):
f = os.path.join(dirName, f)
baseName, ext = os.path.splitext(f)
if ext == '.xc':
print "Processing [", f, "]"
xc(f)
elif ext == '.x':
print "Processing [", f, "]"
x(f)
elif os.path.isdir(f):
print "\nDescending into directory", f
process_directory(dirName=os.path.join(dirName, f))
else:
print "Not processing", f
函数^{} 递归地遍历目录树,返回所有文件名和子目录名。
因此,您只需检测文件名中的
.x
和.xc
扩展名,并在执行时应用您的函数(下面是未经测试的代码):这假设可以对文件名调用
x
和xc
;或者,可以先读取内容,然后将其作为字符串传递给函数。似乎是使用递归的好地方:
我希望我没有错过你问题的重点。
相关问题 更多 >
编程相关推荐