Python基礎 使用with結構開啟多個檔案
阿新 • • 發佈:2018-11-08
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
考慮如下的案例:
同時開啟三個檔案,檔案行數一樣,要求實現每個檔案依次讀取一行,然後輸出,我們先來看比較容易想到的寫法:
with open(filename1, 'rb') as fp1: with open(filename2, 'rb') as fp2: with open(filename3, 'rb') as fp3: for i in fp1: j = fp2.readline() k = fp3.readline() print(i, j, k)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
注意這裡只能對單個檔案進行for迴圈讀取,不能寫成:
for i, j, k in fp1, fp2, fp3: print(i, j, k)
- 1
- 2
但可使用強大的zip操作:
for i, j, k in zip(fp1, fp2, fp3): print(i, j, k)
- 1
- 2
這樣層層的巢狀未免囉嗦,with結構支援一種更簡潔的寫法:
with open(filename1, 'rb') as fp1, open(filename2, 'rb') as fp2, open(filename3, 'rb') as fp3: for i in fp1: j = fp2.readline() k = fp3.readline() print(i, j, k)
- 1
- 2
- 3
- 4
- 5
- 6
或者使用更為優雅的寫法,此時需要contextlib語法糖:
from contextlib improt ExitStackwith ExitStack() as stack: files = [stack.enter_context(open(fname)) for fname in [filename1, filename2, filename3]] for i, j, k in zip(files[0], files[1], files[2]): print(i, j, k)
- 1
- 2
- 3
- 4
- 5