python打开多个文件并一次使用多个目录 [英] python opening multiple files and using multiple directories at once

查看:1079
本文介绍了python打开多个文件并一次使用多个目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用open打开两个文件,现在如果我使用同样的方法进行两个目录,

I can open two files at once using with open, now if i am going through two directories using this same method,

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中的行))具有相同的效果作为您发布的原始代码,除非您想要处理两个文件中的相应行,否则无效。

Your pseudocode (for line in f and f1, x.write(line in f) y.write(line in f1)) has the same effect as the original code you posted, and isn't useful unless there is something about the corresponding lines in the two files that you want to process.

但是您可以使用 zip 组合迭代以获得您想要的

But you can use zip to combine iterables to get what you want

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) 




  • 我使用 \ 将所有文件对象放在一个中,使用子句来转义新行,以便python将其视为单行

    • I put all of the file objects in a single with clause using \ to escape the new line so that python sees it as a single line

      zip 的各种排列将迭代合并到一系列元组。

      The various permutations of zip combine iterables into a sequence of tuples.

      我选择了izip_longest,因为它将继续从两个文件发出行,对于首先清空的文件使用None,直到所有行都被使用。 如果r1_line ... 只是确保我们没有被完全消耗的Nones文件。

      I chose izip_longest because it will continue to emit lines from both files, using None for the files that empty first, until all lines are consumed. if r1_line ... just makes sure we aren't at the Nones for file that has been fully consumed.

      这是一个奇怪的做法 - 对于你给出的例子,这不是更好的选择。

      This is a strange way to do things - for the example you've given, it's not the better choice.

      这篇关于python打开多个文件并一次使用多个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆