Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python一次打开多个文件并使用多个目录_Python_Loops_Directory - Fatal编程技术网

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

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)

我可以用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) 
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行…只需确保我们对已完全使用的文件不感兴趣

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


您想将两个文件合并为一个文件吗?不,我要做的是在两个不同的目录中打开两个不同的文件,查找相同的字符串并编辑它们,唯一的区别是它们位于不同的目录@Smushi。你的问题是什么?你说这两个文件没有打开?如果你只是想减少冗余,你可以将它包装在一个函数中,该函数将你想要使用的目录作为参数。这将减少代码的重复使用。