Python通過 open() 函數(shù)讀取文件,常用模式包括 'r'(文本只讀)和 'rb'(二進(jìn)制)。使用 with 語句可自動(dòng)關(guān)閉文件,避免資源泄漏。還可以根據(jù)需求增加異常處理、編碼指定等其他參數(shù)。大文件建議分塊讀取,或用 readlines() 獲取行列表。二進(jìn)制文件需用 'rb' 模式。
python讀取文件的操作方法
在Python中,讀取文件是常見的操作,主要通過內(nèi)置的 open() 函數(shù)實(shí)現(xiàn)。以下是詳細(xì)的操作方法和示例:
1. 基本讀取方法
(1) 讀取整個(gè)文件
python# 打開文件并讀取全部內(nèi)容(返回字符串)with open('example.txt', 'r', encoding='utf-8') as file:content = file.read()print(content)
參數(shù)說明:
'r':以只讀模式打開。
encoding='utf-8':指定編碼。
with 語句:自動(dòng)關(guān)閉文件,避免資源泄漏。
(2) 逐行讀取
python# 讀取文件并逐行處理with open('example.txt', 'r', encoding='utf-8') as file:for line in file: # 文件對(duì)象是可迭代的print(line.strip()) # strip() 去除行尾換行符
(3) 讀取所有行到列表
pythonwith open('example.txt', 'r', encoding='utf-8') as file:lines = file.readlines() # 返回列表,每行一個(gè)元素print(lines[0]) # 訪問第一行
2. 高級(jí)讀取方法
(1) 讀取大文件
python# 避免內(nèi)存不足,分塊讀取(如每次讀取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. 二進(jìn)制文件讀取
python# 讀取圖片、PDF等二進(jìn)制文件with open('image.jpg', 'rb') as file: # 'rb' 表示二進(jìn)制模式data = file.read()print(f"讀取了 {len(data)} 字節(jié)")
4. 注意事項(xiàng)
文件路徑:
相對(duì)路徑(如 'data/example.txt')基于當(dāng)前腳本目錄。
絕對(duì)路徑(如 '/home/user/data.txt')需確保權(quán)限正確。
異常處理:
pythontry:with open('nonexistent.txt', 'r') as file:print(file.read())except FileNotFoundError:print("文件不存在!")except IOError:print("讀取文件時(shí)出錯(cuò)!")
文件關(guān)閉:
使用 with 語句會(huì)自動(dòng)關(guān)閉文件,手動(dòng)打開時(shí)需調(diào)用 file.close()。
5. 完整示例
python# 綜合示例:統(tǒng)計(jì)文件行數(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"錯(cuò)誤:文件 {file_path} 不存在!")
總結(jié)
文本文件:用 read()、readlines() 或遍歷文件對(duì)象。
大文件:分塊讀取(read(size))。
二進(jìn)制文件:用 'rb' 模式。
推薦:始終使用 with 和異常處理確保安全。
在Python中,讀取文件是一個(gè)常見的操作,在數(shù)據(jù)處理工作中文件讀取是基礎(chǔ)操作但細(xì)節(jié)決定成敗,以上就是python讀取文件的操作方法介紹。