我正在嘗試在休息呼叫中發送檔案物件并希望接收其回應,但 POST 方法可能會引發一些錯誤,并且此后檔案將不會關閉。所以,我也在 except 塊中添加了 close 。但是當我運行代碼時,第一個 api (GET) 會引發一些錯誤,并且除了它會關閉從未打開的檔案并引發另一個錯誤。只有在打開檔案時,我才知道如何處理 close() 。
這是我的代碼基本結構:
try:
url = "some url"
# This Response may throw some error
response = requests.get(url = url, headers=headers,params=params)
file = open("file.txt","r")
# This Response may throw some error
response = requests.post(url = url, headers=headers,params=params, files=file)
file.close()
except:
file.close()
uj5u.com熱心網友回復:
在這種情況下使用with 陳述句。使用 with 意味著檔案將在您離開塊后立即關閉。這是有益的,因為關閉檔案很容易被遺忘并占用您不再需要的資源。因此,在這種情況下,您不必在任何地方指定file.close(),因為 with 塊將在內部處理此問題。
代碼
try:
url = "some url"
# This Response may throw some error
response = requests.get(url = url, headers=headers,params=params)
with open("file.txt","r") as file:
# This Response may throw some error
response = requests.post(url = url, headers=headers,params=params, files=file)
except Exception as exception:
# Just Handle your exception here
print(exception)
uj5u.com熱心網友回復:
您可以設定一些標志變數來了解檔案是否成功打開,以及是否需要關閉:
file_was_opened = False
file_was_closed = False
try:
# some code that may throw exceptions
file = open('filename')
file_was_opened = True
# some other code that may throw exceptions
file.close()
file_was_closed = True
except:
# handle the exception
if file_was_opened and not file_was_closed:
file.close()
但是,更好的方法是使用背景關系管理器。這是一種打開檔案的特殊方式,它保證無論發生什么其他情況,它都會被關閉。
with open('filename') as file:
try:
# some code that may throw exceptions
except:
# handle the exception
# after the "with" block is done, the file is guaranteed to be
# closed
uj5u.com熱心網友回復:
您的第一個問題是您依賴于您的try塊中發生的某些事情。如果你的檔案不存在,你會得到一個不同的例外(例外捕獲也會失敗)。為了解決這個問題,首先檢查你的file變數是否存在:
if "file" in locals():
現在如果是,請確保它尚未關閉,如果它是打開的,請關閉它。
# ... within the if block
if not file.closed:
file.close()
現在你可以自由處理你的例外了。另一個(坦率地說是更好的解決方案)是with宣告,在這個答案中進行了解釋,但為了完整起見,我將在這里舉一個例子:
with open("myfile.txt") as file:
try:
do_things()
except:
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/441711.html
標籤:Python python-3.x 文件 蟒蛇请求
