python打开多个文件并在上使用多个目录

2024-04-26 18:33:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以用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)

将这些合并到一个方法中


Tags: 文件path方法in目录forifos
1条回答
网友
1楼 · 发布于 2024-04-26 18:33:10

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

但是您可以使用zip组合ITerable来获得您想要的

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) 
  • 我将所有的file对象放在一个with子句中,使用\来转义新行,以便python将其视为一行

  • zip的各种排列组合成一个元组序列。

  • 我选择izip_longest是因为它将继续从两个文件发出行,对先清空的文件使用None,直到所有的行都被消耗掉。if r1_line ...只需确保我们不在已被完全使用的文件的Nones中。

  • 这是一种奇怪的做事方式——比如你举的例子,这并不是更好的选择。

相关问题 更多 >