如何在Python中使用“open”打开多个文件?

时间:2021-01-05 00:30:47

I want to change a couple of files at one time, iff I can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the with statement:

我想一次换几个文件,我可以给所有人写。我想知道我是否可以将多个open调用与with语句组合在一起:

try:
  with open('a', 'w') as a and open('b', 'w') as b:
    do_something()
except IOError as e:
  print 'Operation failed: %s' % e.strerror

If that's not possible, what would an elegant solution to this problem look like?

如果这是不可能的,那么这个问题的优雅解决方案是什么样的呢?

5 个解决方案

#1


687  

As of Python 2.7 (or 3.1 respectively) you can write

如Python 2.7(或3.1),您可以编写。

with open('a', 'w') as a, open('b', 'w') as b:
    do_something()

In earlier versions of Python, you can sometimes use contextlib.nested() to nest context managers. This won't work as expected for opening multiples files, though -- see the linked documentation for details.

在Python的早期版本中,您有时可以使用contextlib.嵌套()来嵌套上下文管理器。不过,这不会像预期的那样打开多个文件,详情请参阅链接文档。

#2


81  

Just replace and with , and you're done:

只是替换和替换,你就完成了:

try:
    with open('a', 'w') as a, open('b', 'w') as b:
        do_something()
except IOError as e:
    print 'Operation failed: %s' % e.strerror

#3


31  

For opening many files at once or for long file paths, it may be useful to break things up over multiple lines. From the Python Style Guide as suggested by @Sven Marnach in comments to another answer:

要一次性打开多个文件或长文件路径,可以将多个文件拆分为多个行。从@Sven Marnach建议的Python风格指南到另一个答案:

with open('/path/to/InFile.ext', 'r') as file_1, \
     open('/path/to/OutFile.ext', 'w') as file_2:
    file_2.write(file_1.read())

#4


5  

Nested with statements will do the same job, and in my opinion, are more straightforward to deal with.

嵌套语句将完成相同的工作,在我看来,更容易处理。

Let's say you have inFile.txt, and want to write it into two outFile's simultaneously.

假设你有inFile。txt,并想把它同时写入两个outFile。

with open("inFile.txt", 'r') as fr:
    with open("outFile1.txt", 'w') as fw1:
        with open("outFile2.txt", 'w') as fw2:
            for line in fr.readlines():
                fw1.writelines(line)
                fw2.writelines(line)

EDIT:

编辑:

I don't understand the reason of the downvote. I tested my code before publishing my answer, and it works as desired: It writes to all of outFile's, just as the question asks. No duplicate writing or failing to write. So I am really curious to know why my answer is considered to be wrong, suboptimal or anything like that.

我不明白为什么要投反对票。在发布我的答案之前,我测试了我的代码,并且它的工作方式是理想的:它写到了所有的outFile,就像这个问题问的一样。没有重复的写作或没有写作。所以我很好奇为什么我的答案被认为是错误的,次优的或者类似的。

#5


1  

With python 2.6 It will not work, we have to use below way to open multiple files:

对于python 2.6,它将不起作用,我们必须使用下面的方法来打开多个文件:

with open('a', 'w') as a:
    with open('b', 'w') as b:

#1


687  

As of Python 2.7 (or 3.1 respectively) you can write

如Python 2.7(或3.1),您可以编写。

with open('a', 'w') as a, open('b', 'w') as b:
    do_something()

In earlier versions of Python, you can sometimes use contextlib.nested() to nest context managers. This won't work as expected for opening multiples files, though -- see the linked documentation for details.

在Python的早期版本中,您有时可以使用contextlib.嵌套()来嵌套上下文管理器。不过,这不会像预期的那样打开多个文件,详情请参阅链接文档。

#2


81  

Just replace and with , and you're done:

只是替换和替换,你就完成了:

try:
    with open('a', 'w') as a, open('b', 'w') as b:
        do_something()
except IOError as e:
    print 'Operation failed: %s' % e.strerror

#3


31  

For opening many files at once or for long file paths, it may be useful to break things up over multiple lines. From the Python Style Guide as suggested by @Sven Marnach in comments to another answer:

要一次性打开多个文件或长文件路径,可以将多个文件拆分为多个行。从@Sven Marnach建议的Python风格指南到另一个答案:

with open('/path/to/InFile.ext', 'r') as file_1, \
     open('/path/to/OutFile.ext', 'w') as file_2:
    file_2.write(file_1.read())

#4


5  

Nested with statements will do the same job, and in my opinion, are more straightforward to deal with.

嵌套语句将完成相同的工作,在我看来,更容易处理。

Let's say you have inFile.txt, and want to write it into two outFile's simultaneously.

假设你有inFile。txt,并想把它同时写入两个outFile。

with open("inFile.txt", 'r') as fr:
    with open("outFile1.txt", 'w') as fw1:
        with open("outFile2.txt", 'w') as fw2:
            for line in fr.readlines():
                fw1.writelines(line)
                fw2.writelines(line)

EDIT:

编辑:

I don't understand the reason of the downvote. I tested my code before publishing my answer, and it works as desired: It writes to all of outFile's, just as the question asks. No duplicate writing or failing to write. So I am really curious to know why my answer is considered to be wrong, suboptimal or anything like that.

我不明白为什么要投反对票。在发布我的答案之前,我测试了我的代码,并且它的工作方式是理想的:它写到了所有的outFile,就像这个问题问的一样。没有重复的写作或没有写作。所以我很好奇为什么我的答案被认为是错误的,次优的或者类似的。

#5


1  

With python 2.6 It will not work, we have to use below way to open multiple files:

对于python 2.6,它将不起作用,我们必须使用下面的方法来打开多个文件:

with open('a', 'w') as a:
    with open('b', 'w') as b: