python打开多个文件并一次使用多个目录

时间:2014-11-13 01:02:45

标签: python loops directory

我可以使用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) 
with open(file2, 'a') as y:
   for line in f1:
      if "string" in line:
          y.write(line)

将这些合并为一个方法

1 个答案:

答案 0 :(得分:1)

您的伪代码(for line in f and f1, x.write(line in f) y.write(line in f1))与您发布的原始代码具有相同的效果,除非您要处理的两个文件中存在相应的行,否则它不会有用。

但是你可以使用zip组合迭代来获得你想要的东西

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,直到消耗掉所有行。 if r1_line ...只是确保我们没有完全消费的Nones文件。

  • 这是一种奇怪的做事方式 - 就你所给出的例子而言,它不是更好的选择。

相关问题