Python通過 open() 函數(shù)讀取文件,常用模式包括 'r'(文本只讀)和 'rb'(二進制)。使用 with 語句可自動關閉文件,避免資源泄漏。還可以根據(jù)需求增加異常處理、編碼指定等其他參數(shù)。大文件建議分塊讀取,或用 readlines() 獲取行列表。二進制文件需用 'rb' 模式。
python讀取文件的操作方法
在Python中,讀取文件是常見的操作,主要通過內置的 open() 函數(shù)實現(xiàn)。以下是詳細的操作方法和示例:
1. 基本讀取方法
(1) 讀取整個文件
python# 打開文件并讀取全部內容(返回字符串)with open('example.txt', 'r', encoding='utf-8') as file:content = file.read()print(content)
參數(shù)說明:
'r':以只讀模式打開。
encoding='utf-8':指定編碼。
with 語句:自動關閉文件,避免資源泄漏。
(2) 逐行讀取
python# 讀取文件并逐行處理with open('example.txt', 'r', encoding='utf-8') as file:for line in file: # 文件對象是可迭代的print(line.strip()) # strip() 去除行尾換行符
(3) 讀取所有行到列表
pythonwith open('example.txt', 'r', encoding='utf-8') as file:lines = file.readlines() # 返回列表,每行一個元素print(lines[0]) # 訪問第一行

2. 高級讀取方法
(1) 讀取大文件
python# 避免內存不足,分塊讀取(如每次讀取1024字節(jié))with open('large_file.txt', 'r', encoding='utf-8') as file:while True:chunk = file.read(1024) # 每次讀取1024字節(jié)if not chunk:breakprint(chunk)
(2) 使用 pathlib
pythonfrom pathlib import Pathcontent = Path('example.txt').read_text(encoding='utf-8')print(content)
3. 二進制文件讀取
python# 讀取圖片、PDF等二進制文件with open('image.jpg', 'rb') as file: # 'rb' 表示二進制模式data = file.read()print(f"讀取了 {len(data)} 字節(jié)")
4. 注意事項
文件路徑:
相對路徑(如 'data/example.txt')基于當前腳本目錄。
絕對路徑(如 '/home/user/data.txt')需確保權限正確。
異常處理:
pythontry:with open('nonexistent.txt', 'r') as file:print(file.read())except FileNotFoundError:print("文件不存在!")except IOError:print("讀取文件時出錯!")
文件關閉:
使用 with 語句會自動關閉文件,手動打開時需調用 file.close()。
5. 完整示例
python# 綜合示例:統(tǒng)計文件行數(shù)和詞數(shù)file_path = 'example.txt'try:with open(file_path, 'r', encoding='utf-8') as file:lines = file.readlines()word_count = sum(len(line.split()) for line in lines)print(f"行數(shù): {len(lines)}, 詞數(shù): {word_count}")except FileNotFoundError:print(f"錯誤:文件 {file_path} 不存在!")
總結
文本文件:用 read()、readlines() 或遍歷文件對象。
大文件:分塊讀取(read(size))。
二進制文件:用 'rb' 模式。
推薦:始終使用 with 和異常處理確保安全。
在Python中,讀取文件是一個常見的操作,在數(shù)據(jù)處理工作中文件讀取是基礎操作但細節(jié)決定成敗,以上就是python讀取文件的操作方法介紹。