有一个包含以下文件的目录:
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和所有文件名为的文件,在它旁边(如果匹配),它们的内容应该合并到一个名为merge_file的新文件中。与testfile匹配但已关闭的其他文件,其文件名应打印在新的_文件中。 ab_列表bd_列表和mno_列表的内容应合并到top_文件中 输出应该是 新文件:
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))
我想从第一行读取,但它给出了一个称为索引错误的错误:列表超出范围。当前代码从第4行读取
假设目录名为
Folder
,并且在该目录中有另一个名为folder
的目录,此代码只执行以下操作:相关问题 更多 >
编程相关推荐