【问题标题】:python opening multiple files and using multiple directories at oncepython打开多个文件并一次使用多个目录
【发布时间】:2014-11-13 01:02:44
【问题描述】:

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

将这些合并到一个方法中

【问题讨论】:

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

标签: python loops directory


【解决方案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 ... 只是确保我们没有处于已完全消耗的文件的无状态。

  • 这是一种奇怪的做事方式 - 对于您给出的示例,这不是更好的选择。

【讨论】:

    猜你喜欢
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 2016-12-15
    • 2015-06-23
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多