Python中的WITH語句有什麼用途?

王林
發布: 2023-08-18 22:53:14
轉載
1832 人瀏覽過

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迴圈遍歷給定文字檔案的每一行。

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

Example

的中文翻譯為:

範例

# 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區塊

Example

的中文翻譯為:

範例

# 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的變數。

  • 最後,在冒號後面的with區塊中放置將與取得的資源一起執行的程式碼。

  • 當此程式碼執行完成時,__exit__() 方法會自動呼叫。在這種情況下,它會關閉文件。

如何撰寫您的上下文管理器方法?

之前寫的上下文管理器是一個類,但是如果你想建立一個類似open()函數的上下文管理器方法呢? Python也允許你寫上下文管理器方法。

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

Example

的中文翻譯為:

範例

# 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

的翻譯為:

exampleFile.txt

Hello tutorialsPoint python
登入後複製
登入後複製

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

結論

我們在本文中學習如何使用with語句和範例。

以上是Python中的WITH語句有什麼用途?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!