2017年8月12日 星期六

[ Python 常見問題 ] How can I open multiple files using “with open” in Python?

Source From Here 
Question 
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. If that's not possible, what would an elegant solution to this problem look like? 

How-To 
As of Python 2.7 (or 3.1 respectively) you can write 
  1. with open('a''w') as a, open('b''w') as b:  
  2.     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.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...