How can I open multiple files using “with open” in Python?
我想一次修改几个文件,如果我能把它们都写下来。我想知道我是否可以将多个打开的调用与
1 2 3 4 5 | 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 |
如果不可能的话,这个问题的优雅解决方案会是什么样子?
的Python 2.7(或3.1,分别),你可以写
1 2 | with open('a', 'w') as a, open('b', 'w') as b: do_something() |
在早期版本的Python,你可以有时使用
在罕见的病例,你想打开一些文件,所有变量在同一时间,你可以使用Python版
1 2 3 | with ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in filenames] # Do something with"files" |
大部分时间你可设置文件,你可能会想他们,另一开放后,虽然。
只为与你
1 2 3 4 5 | try: with open('a', 'w') as a, open('b', 'w') as b: do_something() except IOError as e: print 'Operation failed: %s' % e.strerror |
如果文件在一次或多次开长文件路径,它可能是有用的在多事情上打破线。从Python风格指南中的建议:"斯文marnach评论另一个答案:
1 2 3 | 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()) |
将该语句的嵌套与工作,在我看来,更多的是straightforward处理。
让我们说你有一个infile.txt和想写它到outfile’s的两个同时进行。
1 2 3 4 5 6 | 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’s的所有的问题,只是问。在失败的重复的写作或写。所以我真的很好奇为什么我知道答案是错误的或被认为是次优的,任何事情都是这样的。
3.3由于Python的类,可以使用从
它可以管理的上下文感知的动态对象的数量,这意味着它将证明是有用的,如果你不知道如何你的许多文件要处理。
在事实上,这是典型的用例文档中提到的管理号码是动态文件。
1 2 3 4 5 | 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 |
如果你有兴趣在这里的细节,是一个通用的例子,为了解释如何操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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) |
输出:
1 2 3 4 5 6 7 8 9 10 | 0 enter X1 enter X2 enter X3 3 exit X3 exit X2 exit X1 0 [1, 2, 3] |
Python 2.6和它不会工作,我们要用下面的方式:开放式多文件
1 2 | with open('a', 'w') as a: with open('b', 'w') as b: |
(8 yrs晚回答),但有一个连接到多个文件,到下面的函数,可以帮助:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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)) |
1 2 3 4 5 6 | 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 ... |