如何遍历目录并将两个文件名传递给我编写的另一个python程序或函数?
下面是我当前的脚本,它有一些输出,它遍历目录并列出文件。我想一次传递两个文件,使用相同的8个字符前缀到另一个python程序或我编写的函数,它将这两个文件作为参数。
我需要在脚本中添加什么才能添加此功能?
# Process 1. Iterate clean directory
os.chdir('/Applications/XAMPP/xamppfiles/htdocs/cleaned_files')
D = {}
fnames = os.listdir(".")
for fname in fnames:
print(fname)
date = fname[0:8] # this extracts the first 8 characters, aka: date
if date not in D:
D[date] = []
print D
从上面的脚本输出
2012_06_Log.csv
2012_06_Summary.csv
2012_07_Log.csv
2012_07_Summary.csv
{'2012_07_': [], '2012_06_': []}
答案 0 :(得分:1)
此处defaultdict
会有所帮助:
from collections import defaultdict
d = defaultdict(list)
for fname in fnames:
date = fname[0:8]
d[date].append(fname)
现在迭代字典值并使用itertools.combinations
获取与每个键相关的所有对:
from itertools import combinations
for f in d.values():
for f1, f2 in combinations(f, 2):
#call your function and pass f1, f2
对代码的简单修复将是:
D = {}
fnames = os.listdir(".")
for fname in fnames:
print(fname)
date = fname[0:8]
if date not in D:
D[date] = []
D[date].append(fname)
#or use: `D.setdefault(date, []).append(fname)`
然后应用itertools.combinations
部分。