如何在 Python 中使用“with open”打开多个文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4617034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I open multiple files using "with open" in Python?
提问by Frantischeck003
I want to change a couple of files at one time, iffI can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the withstatement:
我想一次更改几个文件,如果我可以写入所有文件。我想知道我是否可以将多个 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?
如果这是不可能的,那么这个问题的优雅解决方案会是什么样的?
采纳答案by Sven Marnach
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.nested()嵌套上下文管理器。但是,这在打开多个文件时不会按预期工作 - 有关详细信息,请参阅链接的文档。
In the rare case that you want to open a variable number of files all at the same time, you can use contextlib.ExitStack, starting from Python version 3.3:
在极少数情况下,您想同时打开可变数量的文件,您可以使用contextlib.ExitStack,从 Python 3.3 版开始:
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# Do something with "files"
Most of the time you have a variable set of files, you likely want to open them one after the other, though.
大多数情况下,您有一组可变的文件,但您可能希望一个接一个地打开它们。
回答by Michael
Just replace andwith ,and you're done:
只需替换and为,,你就完成了:
try:
with open('a', 'w') as a, open('b', 'w') as b:
do_something()
except IOError as e:
print 'Operation failed: %s' % e.strerror
回答by Michael Ohlrogge
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 Guideas 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())
回答by FatihAkici
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。没有重复写作或未能写作。所以我真的很想知道为什么我的答案被认为是错误的、次优的或类似的。
回答by Aashutosh jha
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:
回答by timgeb
Since Python 3.3, you can use the class ExitStackfrom the contextlibmodule to safely
open an arbitrary number of files.
因为Python 3.3,你可以使用类ExitStack从contextlib模块到安全地
打开文件的任意数量。
It can manage a dynamicnumber of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.
它可以管理动态数量的上下文感知对象,这意味着如果您不知道要处理多少个文件,它将特别有用。
In fact, the canonical use-case that is mentioned in the documentation is managing a dynamic number of files.
事实上,文档中提到的规范用例是管理动态数量的文件。
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
If you are interested in the details, here is a generic example in order to explain how ExitStackoperates:
如果您对细节感兴趣,这里有一个通用示例来解释如何ExitStack操作:
from contextlib import ExitStack
class X:
num = 1
def __init__(self):
self.num = X.num
X.num += 1
def __repr__(self):
cls = type(self)
return '{cls.__name__}{self.num}'.format(cls=cls, self=self)
def __enter__(self):
print('enter {!r}'.format(self))
return self.num
def __exit__(self, exc_type, exc_value, traceback):
print('exit {!r}'.format(self))
return True
xs = [X() for _ in range(3)]
with ExitStack() as stack:
print(len(stack._exit_callbacks)) # number of callbacks called on exit
nums = [stack.enter_context(x) for x in xs]
print(len(stack._exit_callbacks))
print(len(stack._exit_callbacks))
print(nums)
Output:
输出:
0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]
回答by CONvid19
Late answer (8 yrs), but for someone looking to join multiple files into one, the following function may be of help:
迟到的答案(8 年),但对于希望将多个文件合并为一个的人来说,以下功能可能会有所帮助:
def multi_open(_list):
out=""
for x in _list:
try:
with open(x) as f:
out+=f.read()
except:
pass
# print(f"Cannot open file {x}")
return(out)
fl = ["C:/bdlog.txt", "C:/Jts/tws.vmoptions", "C:/not.exist"]
print(multi_open(fl))
2018-10-23 19:18:11.361 PROFILE [Stop Drivers] [1ms]
2018-10-23 19:18:11.361 PROFILE [Parental uninit] [0ms]
...
# This file contains VM parameters for Trader Workstation.
# Each parameter should be defined in a separate line and the
...

