Python 中 WITH 語句有什麼作用?


在本文中,我們將學習 Python 中的“with”語句及其用途。

  • Python 中的 with 語句用簡單的簡寫替換了 try-catch 塊。

  • 更重要的是,它確保在處理完資源後立即關閉資源。

  • 讀取或寫入檔案是 with 語句的常見用途。

  • 上下文管理器是一個支援 with 語句的函式或類。上下文管理器使您能夠在需要時開啟和關閉資源。

  • 例如,open() 函式是一個上下文管理器。當您使用 with 語句呼叫 open() 函式時,檔案會在您處理完它後自動關閉。

使用“with”語句開啟並讀取檔案

演算法(步驟)

以下是執行所需任務需遵循的演算法/步驟:

  • 使用open()函式(開啟檔案並返回檔案物件作為結果)以只讀模式開啟文字檔案,將檔名和模式作為引數傳遞給它(此處“r”表示只讀模式)。

with open(inputFile, 'r') as fileData:
  • 使用readlines()函式獲取給定文字檔案的行列表。

file.readlines(hint)
  • 使用 for 迴圈遍歷給定文字檔案的每一行。

  • 列印文字檔案的對應行。

示例

# input file path inputFile = "ExampleTextFile.txt" print("The lines of a given Text File are:") # Opening the given file in read-only mode. with open(inputFile, 'r') as fileData: # Read the above file lines using readlines() fileLines = fileData.readlines() # Traverse in the each line of the text file for textLine in fileLines: # printing each line print(textLine)

輸出

The lines of a given Text File are:
Good Morning this is Tutorials Point sample File
Consisting of Specific
Good source codes in Python,Seaborn,Scala
Summary and Explanation

With 關鍵字不僅用於以讀取模式開啟檔案,還用於為開啟的檔案分配別名。

使用“with”語句替換 try-catch 塊

在 Python 中,您可以使用 try-catch 錯誤處理來開啟和寫入檔案。

with語句在後臺替換了以下型別的 try-catch 塊

示例

# opening the file in write mode using the open() function inputFile = open("tutorialsFile.txt", "w") # handling the exceptions using try-catch blocks try: # writing text into the file inputFile.write("Hello tutorialsPoint python") finally: # closing the file inputFile.close()

輸出

Hello tutorialsPoint python

此程式開啟檔案tutorialsFile.txt。如果不存在此類檔案,則程式會建立它。然後,程式碼將“Hello tutorialsPoint python”寫入檔案,然後關閉它。

此方法沒有問題。但是,有一種更優雅的方法可以使用with語句來實現此目的。

現在讓我們使用with語句重新建立前面的示例:

# opening a file in write mode with an alias name using with statement with open("tutorialsFile.txt", "w") as file: # writing text into the file file.write("Hello tutorialsPoint python")

這簡化了程式碼,因為 with 語句可以在檔案使用後處理關閉檔案。因此,通常,使用 with 語句是 Python 中開啟檔案的首選方法。

Python“with”語句和上下文管理器

在處理檔案時,您可能會認為 with 語句僅適用於 open() 函式。但是,情況並非如此。還可以建立支援with語句的類和物件。

上下文管理器是一個支援with語句的類或函式

如果要提高專案中的資源管理,可以使用自己的上下文管理器。要被視為上下文管理器,類必須實現以下兩種方法:

  • __enter__()
  • __exit__()

實現這些方法後,就可以在類的物件上使用 with 語句。

  • 呼叫 with 語句時,會呼叫 __enter__() 方法。

  • 退出 with 塊的範圍時,會呼叫 __exit__()。

建立檔案寫入器上下文管理器

此類與 open() 方法的功能相同

class FileWriter(object): def __init__(self, fileName): self.fileName = fileName def __enter__(self): self.file = open(self.fileName, "w") return self.file def __exit__(self, exception_type, exception_value, traceback): self.file.close()

上述程式的用法

  • 使用 FileWriter(filename),會建立一個新的 FileWriter 物件並呼叫 __enter__ ()。

  • __enter__() 方法用於初始化所需的資源。在本例中,它開啟一個文字檔案。它還必須返回資源的描述符,因此它返回開啟的檔案。

  • as file 將檔案分配給變數 file。

  • 最後,將在冒號後面的 with 塊中放置將使用獲取的資源執行的程式碼。

  • 此程式碼完成執行時,會自動呼叫 __exit__() 方法。在本例中,它關閉檔案。

如何編寫上下文管理器方法?

前面編寫的上下文管理器是一個類,但如果要建立類似於 open() 函式的上下文管理器方法怎麼辦?Python 也允許您編寫上下文管理器方法。

使用contextlib模組將方法轉換為上下文管理器。

示例

# importig the contextmanager from contextlib module from contextlib import contextmanager # Marking the file_open() function as a context manager # using contextmanager decorator @contextmanager def file_open(name): try: file = open(name, "w") yield file finally: file.close() with file_open("exampleFile.txt") as file: file.write("Hello tutorialsPoint python")

exampleFile.txt

Hello tutorialsPoint python

在這裡,我們建立了一個新函式並使用 with 關鍵字命名它。當我們呼叫該函式時,它會嘗試以寫入模式開啟指定的檔案並返回結果。如果發生錯誤,檔案將被關閉。

結論

我們在本文中學習瞭如何使用 with 語句以及示例。

更新於: 2022-09-22

6K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.