python一次打开多个文件并使用多个目录
我可以用with open同时打开两个文件,现在如果我用同样的方法浏览两个目录python一次打开多个文件并使用多个目录,python,loops,directory,Python,Loops,Directory,我可以用with open同时打开两个文件,现在如果我用同样的方法浏览两个目录 f = open(os.path.join('./directory/', filename1), "r") f2 = open(os.path.join('./directory2/', filename1) "r") with open(file1, 'a') as x: for line in f: if "strin" in line: x.write(line)
f = open(os.path.join('./directory/', filename1), "r")
f2 = open(os.path.join('./directory2/', filename1) "r")
with open(file1, 'a') as x:
for line in f:
if "strin" in line:
x.write(line)
with open(file2, 'a') as y:
for line in f1:
if "string" in line:
y.write(line)
将这些代码合并到一个方法中您的伪代码(对于f和f1中的行,x.write(f中的行)y.write(f1中的行)
)与您发布的原始代码具有相同的效果,除非您要处理的两个文件中的对应行中有某些内容,否则它不会有用
但是您可以使用zip
组合iterables来获得您想要的东西
import itertools
with open(os.path.join('./directory', filename1)) as r1, \
open(os.path.join('./directory2', filename1)) as r2, \
open(file1, 'a') as x, \
open(file2, 'a') as y:
for r1_line, r2_line in itertools.izip_longest(r1, r2):
if r1_line and "string" in line:
x.write(r1_line)
if r2_line and "string" in line:
y.write(r1_line)
- 我将所有文件对象放在一个
子句中,使用with
转义新行,以便python将其视为一行\
的各种排列组合成一个元组序列zip
- 我选择izip_longest是因为它将继续从这两个文件中发出行,对首先为空的文件使用None,直到所有行都用完为止<代码>如果r1\u行…只需确保我们对已完全使用的文件不感兴趣
- 这是一种奇怪的做事方式——就你给出的例子而言,这不是更好的选择