Python 文件讀寫的八大實用方法
Python作為一門強大的編程語言,不僅在數據處理、機器學習等領域大放異彩,其文件操作功能也非常強大且靈活。無論是讀取配置文件、處理日志文件,還是編寫腳本進行文件自動化管理,Python都提供了豐富的方法。今天,我們就來探討Python文件讀寫的8大實用方法,并通過實際代碼示例逐步深入。
1. 使用open函數讀取文件
在Python中,讀取文件最基本的方式是使用內置的open函數。這個函數返回一個文件對象,你可以用它來讀取文件內容。
# 打開文件并讀取內容
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
解釋:
- open('example.txt', 'r', encoding='utf-8'):打開當前目錄下的example.txt文件,模式'r'表示讀取模式,encoding='utf-8'指定文件編碼。
- with語句確保文件在讀取完畢后自動關閉。
- file.read():讀取文件全部內容。
2. 按行讀取文件
對于大文件,一次性讀取全部內容可能會消耗大量內存。按行讀取是一個更好的選擇。
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip()) # strip()去除行尾的換行符
解釋:
- for line in file:逐行讀取文件內容。
- line.strip():去除每行末尾的換行符。
3. 寫入文件
寫入文件同樣使用open函數,但模式要改為'w'(寫入)或'a'(追加)。
# 寫入文件
with open('output.txt', 'w', encoding='utf-8') as file:
file.write('Hello, Python!\n')
file.write('Welcome to file operations.')
# 追加內容到文件
with open('output.txt', 'a', encoding='utf-8') as file:
file.write('\nGoodbye, Python!')
解釋:
- 'w'模式會覆蓋文件原有內容,'a'模式會在文件末尾追加內容。
- file.write():將字符串寫入文件。
4. 使用readlines讀取所有行
readlines方法會讀取文件所有行,并返回一個包含每行內容的列表。
with open('example.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
for line in lines:
print(line.strip())
解釋:
- file.readlines():讀取所有行,每行作為列表的一個元素。
5. 寫入多行
你可以使用writelines方法一次性寫入多行內容。
lines_to_write = ['First line.\n', 'Second line.\n', 'Third line.\n']
with open('output.txt', 'w', encoding='utf-8') as file:
file.writelines(lines_to_write)
解釋:
- writelines接受一個字符串列表,每個字符串代表文件的一行。
6. 使用pickle模塊序列化對象
pickle模塊可以將Python對象序列化為字節流,然后寫入文件,或者從文件中反序列化對象。
import pickle
# 序列化對象并寫入文件
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
with open('data.pkl', 'wb') as file:
pickle.dump(data, file)
# 從文件中反序列化對象
with open('data.pkl', 'rb') as file:
loaded_data = pickle.load(file)
print(loaded_data)
解釋:
- 'wb'和'rb'模式分別用于二進制寫入和讀取。
- pickle.dump(data, file):將data對象序列化并寫入文件。
- pickle.load(file):從文件中反序列化對象。
7. 使用csv模塊處理CSV文件
CSV(逗號分隔值)文件是常見的數據存儲格式。Python的csv模塊提供了方便的接口來讀寫CSV文件。
import csv
# 寫入CSV文件
with open('data.csv', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerows([['Alice', 30, 'New York'], ['Bob', 25, 'Los Angeles']])
# 讀取CSV文件
with open('data.csv', 'r', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(row)
解釋:
- csv.writer(file):創建一個寫入器對象。
- writer.writerow(row)和writer.writerows(rows):寫入一行或多行數據。
- csv.reader(file):創建一個讀取器對象。
- for row in reader:逐行讀取CSV文件內容。
8. 使用json模塊處理JSON文件
JSON(JavaScript Object Notation)是一種輕量級的數據交換格式。Python的json模塊可以方便地進行JSON數據的序列化和反序列化。
import json
# 序列化對象并寫入JSON文件
data = {'name': 'Alice', 'age': 30, 'city': 'New York'}
with open('data.json', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
# 從JSON文件中反序列化對象
with open('data.json', 'r', encoding='utf-8') as file:
loaded_data = json.load(file)
print(loaded_data)
解釋:
- json.dump(data, file, ensure_ascii=False, indent=4):將data對象序列化為JSON格式并寫入文件,ensure_ascii=False確保非ASCII字符正確顯示,indent=4使輸出格式化。
- json.load(file):從文件中反序列化JSON數據。
實戰案例:日志文件分析
假設你有一個日志文件log.txt,內容如下:
2023-10-01 10:00:00 INFO User logged in
2023-10-01 10:05:00 ERROR Invalid credentials
2023-10-01 10:10:00 INFO User logged out
你的任務是統計日志文件中每個日志級別的出現次數。
from collections import defaultdict
log_levels = defaultdict(int)
with open('log.txt', 'r', encoding='utf-8') as file:
for line in file:
timestamp, level, message = line.split(maxsplit=2)
log_levels[level] += 1
print("Log levels count:")
for level, count in log_levels.items():
print(f"{level}: {count}")
輸出:
Log levels count:
INFO: 2
ERROR: 1
分析:- 我們使用defaultdict(int)來統計每個日志級別的出現次數。- 通過line.split(maxsplit=2)將每行日志分割為時間戳、日志級別和消息三部分。- 遍歷文件,更新日志級別的計數。- 最后打印出每個日志級別的出現次數。
總結
本篇文章詳細介紹了Python文件讀寫的8大實用方法,包括基本的文件讀寫操作、逐行讀取、寫入多行、使用pickle、csv和json模塊處理特定格式的文件。通過實際代碼示例,我們逐步深入,從簡單到復雜,展示了每個概念是如何應用的。最后,通過一個實戰案例——日志文件分析,進一步鞏固了所學知識。