我想一次更改几个文件,如果我可以写入所有文件.我想知道我是否能以某种方式将多个开放调用与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
Run Code Online (Sandbox Code Playgroud)
如果那是不可能的,那么这个问题的优雅解决方案会是什么样子?
Sve*_*ach 956
从Python 2.7(或分别为3.1)开始,您可以编写
with open('a', 'w') as a, open('b', 'w') as b:
do_something()
Run Code Online (Sandbox Code Playgroud)
在早期版本的Python中,您有时可以使用
contextlib.nested()
嵌套上下文管理器.但是,这对于打开多个文件不起作用 - 请参阅链接文档以获取详细信息.
在极少数情况下,您希望同时打开可变数量的文件,您可以使用contextlib.ExitStack
,从Python 3.3版开始:
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# Do something with "files"
Run Code Online (Sandbox Code Playgroud)
大多数情况下,如果你有一组可变文件,你可能想要一个接一个地打开它们.
Mic*_*ael 94
只需更换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
Run Code Online (Sandbox Code Playgroud)
Mic*_*gge 50
要一次打开多个文件或长文件路径,在多行中分解可能很有用.从@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())
Run Code Online (Sandbox Code Playgroud)
Fat*_*ici 11
嵌套语句将完成相同的工作,在我看来,更直接的处理.
假设您有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)
Run Code Online (Sandbox Code Playgroud)
编辑:
我不明白downvote的原因.我在发布我的答案之前测试了我的代码,并且它按照需要工作:它写入所有的outFile,就像问题一样.没有重复写入或无法写入.所以我很想知道为什么我的答案被认为是错误的,次优的或类似的.
Chr*_*nds 11
从 Python 3.10 开始,有括号上下文管理器的新功能,它允许使用以下语法:
with (
open("a", "w") as a,
open("b", "w") as b
):
do_something()
Run Code Online (Sandbox Code Playgroud)
因为Python 3.3,你可以使用类ExitStack
从contextlib
模块到安全地
打开文件的任意数量。
它可以管理动态数量的上下文感知对象,这意味着如果您不知道要处理多少文件,它将证明特别有用。
实际上,文档中提到的规范用例正在管理动态数量的文件。
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
Run Code Online (Sandbox Code Playgroud)
如果您对这些细节感兴趣,下面是一个通用示例,以说明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)
Run Code Online (Sandbox Code Playgroud)
输出:
0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
小智 6
使用 python 2.6 它将无法工作,我们必须使用以下方式来打开多个文件:
with open('a', 'w') as a:
with open('b', 'w') as b:
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
264209 次 |
最近记录: |