Python open() 函式



Python open() 函式 是一個 內建函式,用於開啟檔案並返回其對應的檔案物件。要執行檔案操作(例如讀取和寫入),首先需要使用 open() 函式開啟檔案。如果檔案不存在,則 open() 方法會引發 "FileNotFoundError" 異常。

檔案開啟模式

以下是與 open() 函式一起用於開啟檔案的不同檔案開啟模式

  • r − 以只讀模式開啟檔案。

  • w − 當我們想要寫入並截斷檔案時使用。

  • x − 用於建立檔案。如果檔案已存在,則會丟擲錯誤。

  • a − 開啟檔案以在末尾追加文字。

  • b − 指定二進位制模式。

  • t − 指定文字模式。

  • + − 開啟檔案以進行更新。

語法

Python open() 函式的語法如下:

open(file, mode)

引數

Python open() 函式接受兩個引數:

  • file − 此引數表示檔案的路徑或名稱。

  • mode − 它指示我們想要以何種模式開啟檔案。

返回值

Python open() 函式返回一個檔案物件。

open() 函式示例

練習以下示例以瞭解如何在 Python 中使用 open() 函式

示例:使用 open() 函式以讀取模式開啟檔案

以下示例演示如何使用 Python open() 函式。在這裡,我們以只讀模式開啟一個檔案並列印其內容。

with open("newFile.txt", "r") as file:
   textOfFile = file.read()
   print("The file contains the following code:") 
   print(textOfFile)

當我們執行上述程式時,它會產生以下結果:

The file contains the following code:
Hi! Welcome to Tutorialspoint...!!

示例:使用 open() 函式以追加模式開啟檔案

當我們以追加模式開啟檔案(由 "a" 表示)時,該檔案允許我們在其中追加文字。在下面的程式碼中,我們開啟一個檔案以向其中寫入文字。

with open("newFile.txt", "a") as file:
   file.write("\nThis is a new line...")

file.close()
with open("newFile.txt", "r") as file:
   textOfFile = file.read()
   print("The file contains the following text:") 
   print(textOfFile)

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

The file contains the following text:
Hi! Welcome to Tutorialspoint...!!

This is a new line...

示例:使用 open() 函式以讀取模式開啟二進位制檔案

我們還可以讀取並將檔案文字轉換為二進位制格式。我們需要將此操作的模式指定為 "rb"。下面的程式碼演示瞭如何以二進位制格式讀取給定檔案的內容。

fileObj = open("newFile.txt", "rb")
textOfFile = fileObj.read()
print("The binary form of the file text:") 
print(textOfFile)

以上程式碼的輸出如下:

The binary form of the file text:
b'Hi! Welcome to Tutorialspoint...!!\r\n\r\nThis is a new line...'
python_built_in_functions.htm
廣告