Python 檔案 read() 方法



Python 檔案read() 方法讀取檔案內容。預設情況下,此方法讀取整個檔案;如果接受可選引數,則只讀取指定位元組數。即使檔案包含的字元超過指定的數量,檔案中剩餘的字元也會被忽略。如果 read() 方法在獲得所有位元組之前遇到 EOF,則它只讀取檔案中可用的位元組。

此方法僅當檔案以任何讀取模式開啟時才執行。這些讀取模式或者是隻讀模式 (r)、讀寫模式 (r+) 和追加讀取模式 (a+)。

語法

以下是 Python 檔案read() 方法的語法:

fileObject.read(size);

引數

  • size − (可選引數) 這是要從檔案中讀取的位元組數。

返回值

此方法返回以字串形式讀取的位元組。

示例

考慮一個包含 5 行的現有檔案,如下所示:

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

以下示例演示了 Python 檔案 read() 方法的用法。在這裡,我們以讀取模式 (r) 開啟檔案“foo.txt”。然後使用此方法讀取檔案的全部內容(直到 EOF)。

# Open a file
fo = open("foo.txt", "r")
print("Name of the file: ", fo.name)

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

line = fo.read()
print("Read Line: %s" % (line))

# Close opened file
fo.close()

執行上述程式後,將產生以下結果:

Name of the file:  foo.txt
Read Line: This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line 

示例

如果我們將一定數量的位元組作為可選引數傳遞給該方法,則僅從檔案中讀取指定的位元組。

# Open a file
fo = open("foo.txt", "r")
print("Name of the file: ", fo.name)

line = fo.read(5)
print("Read Line: ", line)

# Close opened file
fo.close()

讓我們編譯並執行給定的程式,以產生以下輸出:

Name of the file:  foo.txt
Read Line:  This 

示例

可以在檔案中依次執行讀寫操作。呼叫 read() 方法是為了檢查使用 write() 方法新增到檔案中的內容是否反映在當前檔案中。

在下面的示例中,我們嘗試使用 write() 方法將內容寫入檔案,然後關閉檔案。然後,此檔案再次以讀取 (r) 模式開啟,並使用 read() 方法讀取檔案內容。

# Open a file in write mode
fo = open("foo.txt", "w")
print("Name of the file: ", fo.name)

# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line

# Write a new line
fo.write("This is the new line")

# Close opened file
fo.close()

# Open the file again in read mode
fo = open("foo.txt", "r")

line = fo.read()
print("File Contents:", line)

# Close opened file again
fo.close()

執行上述程式後,輸出將顯示在終端上,如下所示:

Name of the file:  foo.txt
File Contents: This is the new line
python_file_methods.htm
廣告