Python文件讀取基礎
1. 文件打開與關閉
# 基本文件打開
file = open('example.txt', 'r', encoding='utf-8')
# 進行文件操作
file.close()
# 使用with語句(推薦)
with open('example.txt', 'r', encoding='utf-8') as file:
# 進行文件操作
pass # with語句結束時自動關閉文件
文件打開模式:
- ‘r’ – 只讀模式(默認)
- ‘w’ – 寫入模式(覆蓋原有內容)
- ‘a’ – 追加模式
- ‘r+’ – 讀寫模式
- ‘b’ – 二進制模式
2. 文件讀取方法
# 讀取整個文件
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
# 逐行讀取
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip())
# 讀取指定字節數
with open('example.txt', 'r', encoding='utf-8') as file:
chunk = file.read(100) # 讀取100個字符
# 讀取所有行到列表
with open('example.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
# 讀取單行
with open('example.txt', 'r', encoding='utf-8') as file:
line = file.readline()
3. 文件寫入操作
# 寫入字符串
with open('output.txt', 'w', encoding='utf-8') as file:
file.write('Hello, World!n')
file.write('這是第二行')
# 寫入多行
lines = ['第一行n', '第二行n', '第三行n']
with open('output.txt', 'w', encoding='utf-8') as file:
file.writelines(lines)
# 追加內容
with open('output.txt', 'a', encoding='utf-8') as file:
file.write('追加的內容')
4. 文件指針操作
# 移動文件指針
with open('example.txt', 'r', encoding='utf-8') as file:
file.seek(0) # 移動到文件開頭
file.seek(10) # 移動到第10個字節
file.seek(0, 2) # 移動到文件末尾
# 獲取當前位置
position = file.tell()
5. 實用示例
# 讀取CSV文件
def read_csv(filename):
data = []
with open(filename, 'r', encoding='utf-8') as file:
for line in file:
data.append(line.strip().split(','))
return data
# 日誌文件寫入
def write_log(message):
with open('app.log', 'a', encoding='utf-8') as file:
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
file.write(f'[{timestamp}] {message}n')
練習題
-
創建一個文本文件計數器:
- 統計文件中的字符數
- 統計文件中的單詞數
- 統計文件中的行數
-
實現簡單的文件備份程序:
- 讀取原始文件內容
- 創建備份文件名(添加時間戳)
- 將內容寫入備份文件
常見錯誤和注意事項
- 始終使用with語句來確保文件正確關閉
- 注意文件編碼(特別是處理中文時)
- 處理大文件時注意內存使用
- 確保有適當的錯誤處理機制
- 注意文件路徑的正確性
進階提示
- 使用pathlib模組處理文件路徑
- 考慮使用緩衝區大小參數優化性能
- 對於大文件,考慮使用生成器方式讀取
- 注意跨平台的換行符處理