如何使用 Python 讀取文字檔案中的整行內容?


Python 中有多種讀取檔案的方式。將介紹在 Python 中逐行讀取檔案的常用方法。

使用 readlines() 方法

使用此方法,將開啟一個檔案並將其內容劃分為單獨的行。此方法還返回檔案中每一行的列表。為了有效地讀取整個檔案,我們可以使用 readlines() 函式。

以下是一個使用 file.endswith() 方法刪除交換檔案的示例:

示例

以下是如何使用 readlines() 方法逐行讀取文字檔案的示例:

# opening the data file file = open("TutorialsPoint.txt") # reading the file as a list line by line content = file.readlines() # closing the file file.close() print(content)

輸出

以下是上述程式碼的輸出。

['Welcome to Tutorials Point\n', 'This is a new file.\n', 'Reading a file line by line using Python\n', 'Thank You!']

使用 readline() 方法

可以使用 readline() 方法獲取文字檔案的第一行。當我們使用 readline() 方法讀取檔案時,與 readlines() 相比,只會列印一行。

示例

以下是如何使用 readline() 方法讀取文字檔案單行的示例:

file = open("TutorialsPoint.txt") # getting the starting line of the file start_line = file.readline() print(start_line) file.close()

輸出

readline() 函式只返回一行文字。如果要一次讀取所有行,請使用 readline()。

以下是上述程式碼的輸出:

Welcome to Tutorials Point

注意 - 與其等效方法相反,readline() 方法僅從檔案中提取一行。realine() 方法還會在字串末尾新增一個尾隨換行符。

我們還可以使用 readline() 方法為返回的行定義長度。如果沒有指定大小,則將讀取整行。

使用 While 迴圈

您可以使用 while 迴圈逐行讀取指定檔案的內容。首先使用 open() 函式以讀取模式開啟檔案以實現此目的。在 while 迴圈內使用 open() 返回的檔案控制代碼來讀取行。

while 迴圈使用 Python 的 readline() 方法讀取行。當使用 for 迴圈時,當檔案結束時迴圈結束。但是,使用 while 迴圈時,情況並非如此,您必須不斷檢查檔案是否已完成讀取。因此,您可以使用 break 語句在 readline() 方法返回空字串時結束 while 迴圈。

示例

以下是如何使用 while 迴圈逐行讀取文字檔案的示例:

file = open("TutorialsPoint.txt", "r") while file: line = file.readline() print(line) if line == "": break file.close()

輸出

以下是上述程式碼的輸出:

Welcome to Tutorials Point
This is a new file.
Reading a file line by line using Python
Thank You!

使用 for 迴圈

首先使用 Python 的 open() 函式以只讀模式開啟檔案。open() 函式將返回一個檔案控制代碼。在您的 for 迴圈中,使用檔案控制代碼從提供的檔案中一次讀取一行。完成後,使用 close() 函式關閉檔案控制代碼。

示例

以下是如何使用 for 迴圈逐行讀取文字檔案的示例:

file = open("TutorialsPoint.txt", "r") for line in file: print(line) file.close()

輸出

以下是上述程式碼的輸出:

Welcome to Tutorials Point
This is a new file.
Reading a file line by line using Python
Thank You!

使用上下文管理器

任何程式語言都需要對檔案管理採取謹慎的方法。處理檔案時必須小心,以避免損壞。務必記住在開啟檔案後關閉資源。此外,Python 對一次可以開啟的檔案數量有限制。Python 為我們提供了上下文管理器來幫助我們避免這些問題。

如果 Python 使用with語句,則檔案處理將是安全的。

  • 要安全地訪問資原始檔,請使用 with 語句。
  • 當 Python 遇到with塊時,它會建立一個新的上下文。
  • Python 在塊完成執行後自動關閉檔案資源。
  • 上下文的範圍類似於with語句。

示例

以下是如何使用 with 語句逐行讀取文字檔案的示例:

# opening the file with open("TutorialsPoint.txt",'r') as text: # reading the file by using a for loop for line in text: # stripping the newline character from the line print(line.strip())

輸出

這次,使用 for 迴圈讀取檔案行。當我們使用上下文管理器時,只要其控制代碼退出作用域,檔案就會自行關閉。with 語句確保在函式完成處理檔案後正確處理資源。

以下是上述程式碼的輸出

Welcome to Tutorials Point
This is a new file.
Reading a file line by line using Python
Thank You!

更新於: 2022-08-17

14K+ 次檢視

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告