
- Python 基礎
- Python - 首頁
- Python - 概述
- Python - 歷史
- Python - 特性
- Python vs C++
- Python - Hello World 程式
- Python - 應用領域
- Python - 直譯器
- Python - 環境設定
- Python - 虛擬環境
- Python - 基本語法
- Python - 變數
- Python - 資料型別
- Python - 型別轉換
- Python - Unicode 系統
- Python - 字面量
- Python - 運算子
- Python - 算術運算子
- Python - 比較運算子
- Python - 賦值運算子
- Python - 邏輯運算子
- Python - 位運算子
- Python - 成員運算子
- Python - 身份運算子
- Python - 運算子優先順序
- Python - 註釋
- Python - 使用者輸入
- Python - 數字
- Python - 布林值
- Python 控制語句
- Python - 控制流
- Python - 決策制定
- Python - If 語句
- Python - If else
- Python - 巢狀 If
- Python - Match-Case 語句
- Python - 迴圈
- Python - for 迴圈
- Python - for-else 迴圈
- Python - While 迴圈
- Python - break 語句
- Python - continue 語句
- Python - pass 語句
- Python - 巢狀迴圈
- Python 函式 & 模組
- Python - 函式
- Python - 預設引數
- Python - 關鍵字引數
- Python - 僅關鍵字引數
- Python - 位置引數
- Python - 僅位置引數
- Python - 可變引數
- Python - 變數作用域
- Python - 函式註解
- Python - 模組
- Python - 內建函式
- Python 字串
- Python - 字串
- Python - 字串切片
- Python - 修改字串
- Python - 字串連線
- Python - 字串格式化
- Python - 跳脫字元
- Python - 字串方法
- Python - 字串練習
- Python 列表
- Python - 列表
- Python - 訪問列表元素
- Python - 修改列表元素
- Python - 新增列表元素
- Python - 刪除列表元素
- Python - 迴圈遍歷列表
- Python - 列表推導式
- Python - 對列表進行排序
- Python - 複製列表
- Python - 合併列表
- Python - 列表方法
- Python - 列表練習
- Python 元組
- Python - 元組
- Python - 訪問元組元素
- Python - 更新元組
- Python - 解包元組
- Python - 迴圈遍歷元組
- Python - 合併元組
- Python - 元組方法
- Python - 元組練習
- Python 集合
- Python - 集合
- Python - 訪問集合元素
- Python - 新增集合元素
- Python - 刪除集合元素
- Python - 迴圈遍歷集合
- Python - 合併集合
- Python - 複製集合
- Python - 集合運算子
- Python - 集合方法
- Python - 集合練習
- Python 字典
- Python - 字典
- Python - 訪問字典元素
- Python - 修改字典元素
- Python - 新增字典元素
- Python - 刪除字典元素
- Python - 字典檢視物件
- Python - 迴圈遍歷字典
- Python - 複製字典
- Python - 巢狀字典
- Python - 字典方法
- Python - 字典練習
- Python 陣列
- Python - 陣列
- Python - 訪問陣列元素
- Python - 新增陣列元素
- Python - 刪除陣列元素
- Python - 迴圈遍歷陣列
- Python - 複製陣列
- Python - 反轉陣列
- Python - 對陣列進行排序
- Python - 合併陣列
- Python - 陣列方法
- Python - 陣列練習
- Python 檔案處理
- Python - 檔案處理
- Python - 寫入檔案
- Python - 讀取檔案
- Python - 重新命名和刪除檔案
- Python - 目錄
- Python - 檔案方法
- Python - OS 檔案/目錄方法
- Python - OS 路徑方法
- 面向物件程式設計
- Python - OOPs 概念
- Python - 類 & 物件
- Python - 類屬性
- Python - 類方法
- Python - 靜態方法
- Python - 建構函式
- Python - 訪問修飾符
- Python - 繼承
- Python - 多型
- Python - 方法重寫
- Python - 方法過載
- Python - 動態繫結
- Python - 動態型別
- Python - 抽象
- Python - 封裝
- Python - 介面
- Python - 包
- Python - 內部類
- Python - 匿名類和物件
- Python - 單例類
- Python - 包裝類
- Python - 列舉
- Python - 反射
- Python 錯誤 & 異常
- Python - 語法錯誤
- Python - 異常
- Python - try-except 塊
- Python - try-finally 塊
- Python - 丟擲異常
- Python - 異常鏈
- Python - 巢狀 try 塊
- Python - 使用者自定義異常
- Python - 日誌記錄
- Python - 斷言
- Python - 內建異常
- Python 多執行緒
- Python - 多執行緒
- Python - 執行緒生命週期
- Python - 建立執行緒
- Python - 啟動執行緒
- Python - 執行緒連線
- Python - 執行緒命名
- Python - 執行緒排程
- Python - 執行緒池
- Python - 主執行緒
- Python - 執行緒優先順序
- Python - 守護執行緒
- Python - 執行緒同步
- Python 同步
- Python - 執行緒間通訊
- Python - 執行緒死鎖
- Python - 中斷執行緒
- Python 網路
- Python - 網路
- Python - 套接字程式設計
- Python - URL 處理
- Python - 泛型
- Python 庫
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 雜項
- Python - 日期 & 時間
- Python - 數學
- Python - 迭代器
- Python - 生成器
- Python - 閉包
- Python - 裝飾器
- Python - 遞迴
- Python - 正則表示式
- Python - PIP
- Python - 資料庫訪問
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 輸出格式化
- Python - 效能測量
- Python - 資料壓縮
- Python - CGI 程式設計
- Python - XML 處理
- Python - GUI 程式設計
- Python - 命令列引數
- Python - 文件字串
- Python - JSON
- Python - 傳送郵件
- Python - 擴充套件
- Python - 工具/實用程式
- Python - GUIs
- Python 高階概念
- Python - 抽象基類
- Python - 自定義異常
- Python - 高階函式
- Python - 物件內部
- Python - 記憶體管理
- Python - 元類
- Python - 使用元類進行超程式設計
- Python - 模擬和存根
- Python - 猴子補丁
- Python - 訊號處理
- Python - 型別提示
- Python - 自動化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 協程
- Python - 描述符
- Python - 診斷和修復記憶體洩漏
- Python - 不可變資料結構
- Python 有用資源
- Python - 問答
- Python - 線上測驗
- Python - 快速指南
- Python - 參考
- Python - 速查表
- Python - 專案
- Python - 有用資源
- Python - 討論
- Python 編譯器
- NumPy 編譯器
- Matplotlib 編譯器
- SciPy 編譯器
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