Python裡處理檔案with open寫法的由來

2021-09-10 18:18:03 字數 1295 閱讀 8620

使用python讀寫檔案,一開始我們用的是:

f = open('test.txt', 'r')

f.read()

最後一步是呼叫close()方法關閉檔案

f.close()

如果開啟報錯ioerror,那後面的close也不會執行,因此,我們可以使用try語句來容錯:

try: 

f = open('/path/to/file', 'r')

print(f.read())

finally:

if f:

f.close()

但每次這樣寫就太冗長了,於是有了一種優雅的寫法:

with open('/path/to/file', 'r') as f: 

print(f.read())

*************************=with是如何工作的******************************

#!/usr/bin/env python

# with_example01.py

class sample:

def __enter__(self):

print "in __enter__()"

return "foo"

def __exit__(self, type, value, trace):

print "in __exit__()"

def get_sample():

return sample()

with get_sample() as sample:

print "sample:", sample

with 後面跟的語句get_sample()返回的是乙個sample物件

with要求sample物件必須有乙個__enter__()方法,乙個__exit__()方法

當get_sample()返回乙個sample物件時,會呼叫sample的__enter__()方法,__enter__()方法的返回值將賦給as後面的變數

在with後面的**塊丟擲任何異常或者成功執行完成時,__exit__()方法被執行,將呼叫前面返回物件的__exit__()方法。

異常丟擲時,與之關聯的type,value和stack trace傳給__exit__()方法,因此丟擲的異常會被列印出來

所以上面這段**的輸出應該是

in __enter__()

sample: foo

in __exit__()

python輸出到檔案裡

傻乎乎寫了各種print,掛到伺服器上,用screen切視窗,一下子就給刷沒了,所以想著重定向到檔案裡。遇到幾個 坑 這裡當做給自己記錄 1 我想要既能重定向到檔案裡,又能輸出到螢幕上。使用了tee工具,但是沒法反應。原因是 python 中如何乙個 print 語句同時輸出到螢幕且記錄到檔案裡 p...

python檔案處理

def cal input input.txt output output.txt cal方法為主程式,推薦這樣做而不是python.exe xx.py 預設引數為python目錄的兩個txt,如為其他檔案自己指定。infile file input,r 開啟源資料檔案 outfile file o...

python 檔案處理

1.開啟檔案 open a.txt 當前目錄下的a.txt open root a.txt 開啟某個目錄下的檔案 2.按行顯示檔案 a open a.txt a.readline ni hao n a.readline wo xianzai hen xiang ni n a.readline ni ...