答案 0 :(得分:856)
答案 1 :(得分:91)
答案 2 :(得分:43)
一次打开多个文件或长文件路径,在多行中分解可能很有用。从@Sven Marnach建议的Python Style Guide评论到另一个答案:
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())
答案 3 :(得分:8)
嵌套语句会做同样的工作,在我看来,处理起来会更直接。
让我们说你有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)
编辑:
我不理解downvote的原因。我在发布我的答案之前测试了我的代码,它按照需要工作:它写入所有outFile,就像问题一样。没有重复写入或无法写入。所以我很想知道为什么我的答案被认为是错误的,次优的或类似的。
答案 4 :(得分:5)
从 Python 3.10 开始,Parenthesized context managers 有一个新功能,它允许使用以下语法:
with (
open("a", "w") as a,
open("b", "w") as b
):
do_something()
答案 5 :(得分:4)
从Python 3.3开始,您可以使用ExitStack
模块中的类contextlib
安全地
打开任意数量的文件。
它可以管理 dynamic 个上下文感知对象,这意味着如果您不知道要处理多少文件,它将非常有用 >。
实际上,文档中提到的规范用例正在管理动态数量的文件。
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
如果您对这些细节感兴趣,下面是一个通用示例,以说明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)
输出:
0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]
答案 6 :(得分:3)
使用python 2.6它不起作用,我们必须使用以下方式打开多个文件:
with open('a', 'w') as a:
with open('b', 'w') as b:
答案 7 :(得分:1)
最新答案(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
...