【发布时间】:2020-06-15 13:33:45
【问题描述】:
有一个包含文件的目录:
ab_list
bd_list
cd_list
mno_list
hk_list
pd_list
我在此目录之外还有另一个名为 testfile 的文件:
abc
que nw
ab_list ON 8
gs_list ON 9
hk_list OFF 9
bd_list ON 7
cd_list OFF 6
fr_list ON 5
mno_list ON 4
pq_list OFF 6
jk_list ON 7
pd_list OFF 8
我想比较 2 和所有带有文件名和 ON 的文件(如果匹配),它们的内容应该合并到一个名为 merge_file 的新文件中。与 testfile 匹配但为 OFF 的其他文件,其文件名应打印在 new_file 中。 ab_list bd_list 和 mno_list 的内容应该合并到 top_file 输出应该像 新文件:
cd_list OFF no.of lines in file
pd_list OFF no.of lines in file
hk_list OFF no. of lines in file
merge_file (this has all ON merged) no.of lines in file
这是到目前为止的代码:
from pathlib import Path
with open('testfile') as fp:
data = dict([tuple(line.split())for line in fp if line.strip()])
with open('merge_file', 'w') as merge_file, open('match_file', 'w') as match_file:
lines = 0
for fp in Path(r'./test').glob('*_list'):
if fp.name in data:
if data[fp.name] == 'ON':
content = fp.open().readlines()
lines += len(content)
merge_file.write('\n'.join(content) + '\n')
else:
content = fp.open().readlines()
match_file.write(fp.name + ' OFF {}\n'.format(len(content)))
match_file.write('merge_file (this has all ON merged) {}'.format(lines))
我想从第一行读取,但它给出了一个名为 Index Error: list out of range 的错误。当前代码从第 4 行读取。
【问题讨论】:
标签: python python-3.x merge