Python - 讀取檔案



從檔案讀取涉及開啟檔案、讀取其內容,然後關閉檔案以釋放系統資源。Python 提供了幾種從檔案讀取的方法,每種方法都適合不同的用例。

開啟檔案以進行讀取

開啟檔案是讀取其內容的第一步。在 Python 中,您可以使用 open() 函式開啟檔案。此函式至少需要一個引數,即檔名,以及可選的模式,該模式指定開啟檔案的目的。

要開啟檔案以進行讀取,您可以使用模式 'r'。這是預設模式,因此如果您只需要從檔案讀取,則可以省略它。

使用 read() 方法讀取檔案

read() 方法用於在 Python 中讀取檔案的內容。它將檔案的全部內容作為單個字串讀取。當您需要一次處理整個檔案時,此方法特別有用。

語法

以下是 Python 中 read() 方法的基本語法:

file_object.read(size)

其中,

  • file_object 是 open() 函式返回的檔案物件。
  • size 是要從檔案讀取的位元組數。此引數是可選的。如果省略或設定為負值,則該方法會讀取到檔案末尾。

示例

在下面的示例中,我們以讀取模式開啟檔案“example.txt”。然後,我們使用 read() 方法讀取檔案的全部內容:

# Open the file in read mode
file = open('example.txt', 'r')

# Read the entire content of the file
content = file.read()

# Print the content
print(content)

# Close the file
file.close()

執行上述程式碼後,我們將獲得以下輸出:

welcome to Tutorialspoint.

使用 readline() 方法讀取檔案

readline() 方法用於一次從檔案中讀取一行。當您需要逐行處理檔案時,此方法很有用,尤其是在處理大型檔案時,一次讀取全部內容是不切實際的。

語法

以下是 Python 中 readline() 方法的基本語法:

file_object.readline(size)

其中,

  • file_object 是 open() 函式返回的檔案物件。
  • size 是一個可選引數,指定從行中讀取的最大位元組數。如果省略或設定為負值,則該方法會讀取到行尾。

示例

在下面的示例中,我們以讀取模式開啟檔案“example.txt”。然後,我們使用 readline() 方法讀取檔案的首行:

# Open the file in read mode
file = open('example.txt', 'r')

# Read the first line of the file
line = file.readline()

# Print the line
print(line)

# Close the file
file.close()

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

welcome to Tutorialspoint.

使用 readlines() 方法讀取檔案

readlines() 方法讀取檔案中的所有行,並將它們作為字串列表返回。列表中的每個字串都表示檔案中的單行,包括每行末尾的換行符。

當您需要一次處理或分析檔案的全部行時,此方法特別有用。

語法

以下是 Python 中 readlines() 方法的基本語法:

file_object.readlines(hint)

其中,

  • file_object 是 open() 函式返回的檔案物件。
  • hint 是一個可選引數,指定要讀取的位元組數。如果指定,它會讀取最多指定位元組的行,不一定讀取整個檔案。

示例

在此示例中,我們以讀取模式開啟檔案“example.txt”。然後,我們使用 readlines() 方法讀取檔案中的所有行,並將它們作為字串列表返回:

# Open the file in read mode
file = open('example.txt', 'r')

# Read all lines from the file
lines = file.readlines()

# Print the lines
for line in lines:
   print(line, end='')

# Close the file
file.close()

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

welcome to Tutorialspoint.
Hi Surya.
How are you?.

使用“with”語句

Python 中的“with”語句用於異常處理。在處理檔案時,使用“with”語句可以確保在讀取後正確關閉檔案,即使發生異常也是如此。

當您使用with語句開啟檔案時,即使塊內發生錯誤,檔案也會在塊結束時自動關閉。

示例

下面是一個使用with語句開啟、讀取和列印檔案內容的簡單示例:

# Using the with statement to open a file
with open('example.txt', 'r') as file:
   content = file.read()
   print(content)

我們得到以下輸出:

welcome to Tutorialspoint.
Hi Surya.
How are you?.

以二進位制模式讀取檔案

預設情況下,檔案物件的讀/寫操作是在文字字串資料上執行的。如果我們想要處理不同型別的檔案,例如媒體檔案(mp3)、可執行檔案(exe)或圖片(jpg),我們必須透過在讀/寫模式中新增'b'字首以二進位制模式開啟檔案。

寫入二進位制檔案

假設test.bin檔案已以二進位制模式寫入:

# Open the file in binary write mode
with open('test.bin', 'wb') as f:
   data = b"Hello World"
   f.write(data)

示例

要讀取二進位制檔案,我們需要以'rb'模式開啟它。然後在列印之前解碼read()方法的返回值:

# Open the file in binary read mode
with open('test.bin', 'rb') as f:
   data = f.read()
   print(data.decode(encoding='utf-8'))

它將產生以下輸出:

Hello World

從檔案中讀取整數資料

要將整數資料寫入二進位制檔案,應使用to_bytes()方法將整數物件轉換為位元組。

將整數寫入二進位制檔案

下面是如何將整數寫入二進位制檔案的示例:

# Convert the integer to bytes and write to a binary file
n = 25
data = n.to_bytes(8, 'big')

with open('test.bin', 'wb') as f:
   f.write(data)

從二進位制檔案中讀取整數

要從二進位制檔案中讀取回整數資料,請使用from_bytes()方法將read()函式的輸出轉換回整數:

# Read the binary data from the file and convert it back to an integer
with open('test.bin', 'rb') as f:
   data = f.read()
   n = int.from_bytes(data, 'big')
   print(n)

從檔案中讀取浮點數資料

為了處理二進位制檔案中的浮點數資料,我們需要使用Python標準庫中的struct模組。此模組有助於在Python值和表示為Python位元組物件的C結構之間進行轉換。

將浮點數寫入二進位制檔案

要將浮點數資料寫入二進位制檔案,我們使用struct.pack()方法將浮點數轉換為位元組物件:

import struct

# Define a floating-point number
x = 23.50

# Pack the float into a binary format
data = struct.pack('f', x)

# Open the file in binary write mode and write the packed data
with open('test.bin', 'wb') as f:
   f.write(data)

從二進位制檔案中讀取浮點數

要從二進位制檔案中讀取浮點數資料,我們使用struct.unpack()方法將位元組物件轉換回浮點數:

import struct

# Open the file in binary read mode
with open('test.bin', 'rb') as f:
   # Read the binary data from the file
   data = f.read()
    
   # Unpack the binary data to retrieve the float
   x = struct.unpack('f', data)[0]
    
   # Print the float value
   print(x)

使用“r+”模式讀取和寫入檔案

當檔案以讀取模式(使用'r'或'rb')開啟時,除非檔案關閉並以不同的模式重新開啟,否則無法寫入資料。要同時執行讀寫操作,我們將'+'字元新增到mode引數中。使用'w+'或'r+'模式可以啟用write()和read()方法,而無需關閉檔案。

File物件還支援seek()函式,該函式允許將讀/寫指標重新定位到檔案中的任何所需位元組位置。

語法

以下是seek()方法的語法:

fileObject.seek(offset[, whence])

引數

  • offset - 這是檔案內讀/寫指標的位置。

  • whence - 這是可選的,預設為0,表示絕對檔案定位,其他值為1,表示相對於當前位置查詢,2表示相對於檔案末尾查詢。

示例

以下程式以'r+'模式(讀寫模式)開啟檔案,在檔案中查詢特定位置,並從該位置讀取資料:

# Open the file in read-write mode
with open("foo.txt", "r+") as fo:
   # Move the read/write pointer to the 10th byte position
   fo.seek(10, 0)
    
   # Read 3 bytes from the current position
   data = fo.read(3)
    
   # Print the read data
   print(data)

執行上述程式碼後,我們將獲得以下輸出:

rat

在Python中同時讀取和寫入檔案

當檔案以寫入模式(使用'w'或'a')開啟時,無法從中讀取,嘗試這樣做會引發UnsupportedOperation錯誤。

類似地,當檔案以讀取模式(使用'r'或'rb')開啟時,不允許寫入它。要在讀取和寫入之間切換,通常需要關閉檔案並以所需的模式重新開啟它。

要同時執行讀寫操作,可以將'+'字元新增到mode引數中。使用'w+'或'r+'模式可以啟用write()和read()方法,而無需關閉檔案。

此外,File物件支援seek()函式,該函式允許您將讀/寫指標重新定位到檔案中的任何所需位元組位置。

示例

在此示例中,我們以'r+'模式開啟檔案並將資料寫入檔案。seek(0)方法將指標重新定位到檔案開頭:

# Open the file in read-write mode
with open("foo.txt", "r+") as fo:
   # Write data to the file
   fo.write("This is a rat race")

   # Rewind the pointer to the beginning of the file
   fo.seek(0)

   # Read data from the file
   data = fo.read()
   print(data)

從特定偏移量讀取檔案

我們可以使用seek()方法將檔案的當前位置設定為指定的偏移量。

  • 如果檔案使用'a'或'a+'以追加模式開啟,則在下次寫入時將撤消任何seek()操作。
  • 如果檔案僅以追加模式使用'a'開啟以進行寫入,則此方法本質上是無操作的,但對於以啟用讀取的追加模式開啟的檔案(模式'a+')仍然有用。
  • 如果檔案使用't'以文字模式開啟,則只有tell()返回的偏移量才是合法的。使用其他偏移量會導致未定義的行為。

請注意,並非所有檔案物件都是可查詢的。

示例

以下示例演示如何使用seek()方法對檔案執行同時讀寫操作。檔案以w+模式(讀寫模式)開啟,添加了一些資料,然後在特定位置讀取和修改檔案:

# Open a file in read-write mode
fo = open("foo.txt", "w+")

# Write initial data to the file
fo.write("This is a rat race")

# Seek to a specific position in the file
fo.seek(10, 0)

# Read a few bytes from the current position
data = fo.read(3)
print("Data read from position 10:", data)

# Seek back to the same position
fo.seek(10, 0)

# Overwrite the earlier contents with new text
fo.write("cat")

# Rewind to the beginning of the file
fo.seek(0, 0)

# Read the entire file content
data = fo.read()
print("Updated file content:", data)

# Close the file
fo.close()

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

Data read from position 10: rat
Updated file content: This is a cat race
廣告