Python讀寫txt文件的多種方法
引言
文本文件(.txt)是最基礎、最通用的數(shù)據(jù)存儲格式之一,廣泛應用于日志記錄、配置文件、數(shù)據(jù)交換等場景。Python提供了簡單易用的內(nèi)置方法來讀寫txt文件,無需額外安裝庫。本文將詳細介紹Python中讀寫txt文件的各種方法,包括基礎操作和高級技巧。
1. 寫入txt文件
1.1 使用open()和write()方法
這是最基本的寫入方法:
# 打開文件進行寫入(如果文件不存在會自動創(chuàng)建)
with open('example.txt', 'w', encoding='utf-8') as file:
file.write("這是第一行文本\n")
file.write("這是第二行文本\n")
file.write("這是第三行文本\n")
參數(shù)說明:
'w':寫入模式(會覆蓋已存在的文件)encoding='utf-8':指定編碼(推薦始終使用UTF-8)with語句:確保文件正確關閉,即使發(fā)生異常
1.2 寫入多行內(nèi)容
使用writelines()方法可以一次性寫入多行:
lines = ["第一行\(zhòng)n", "第二行\(zhòng)n", "第三行\(zhòng)n"]
with open('multiline.txt', 'w', encoding='utf-8') as file:
file.writelines(lines)
1.3 追加內(nèi)容到文件
使用'a'模式可以在文件末尾追加內(nèi)容而不覆蓋原有內(nèi)容:
with open('example.txt', 'a', encoding='utf-8') as file:
file.write("這是追加的內(nèi)容\n")
1.4 格式化寫入
結合f-string或format()方法可以寫入動態(tài)內(nèi)容:
name = "張三"
age = 25
with open('formatted.txt', 'w', encoding='utf-8') as file:
file.write(f"姓名: {name}, 年齡: {age}\n")
# 或者使用format
file.write("職業(yè): {}\n".format("工程師"))
2. 讀取txt文件
2.1 讀取整個文件
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
2.2 逐行讀取
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file: # 迭代器方式逐行讀取
print(line.strip()) # strip()去除行尾換行符
2.3 讀取所有行到列表
with open('example.txt', 'r', encoding='utf-8') as file:
lines = file.readlines() # 返回包含所有行的列表
for i, line in enumerate(lines, 1):
print(f"第{i}行: {line.strip()}")
2.4 處理大文件
對于大文件,建議使用逐行讀取或分塊讀取以避免內(nèi)存問題:
# 方法1:逐行讀?。▋?nèi)存友好)
with open('large_file.txt', 'r', encoding='utf-8') as file:
for line in file:
process_line(line) # 處理每一行的函數(shù)
# 方法2:分塊讀取
chunk_size = 1024 * 1024 # 1MB
with open('large_file.txt', 'r', encoding='utf-8') as file:
while True:
chunk = file.read(chunk_size)
if not chunk:
break
process_chunk(chunk) # 處理每個塊的函數(shù)
3. 文件路徑處理
3.1 相對路徑與絕對路徑
# 相對路徑(相對于當前工作目錄)
with open('./data/example.txt', 'r') as file:
...
# 絕對路徑(推薦使用os.path或pathlib處理跨平臺路徑)
import os
file_path = os.path.join('C:', 'Users', 'username', 'Documents', 'example.txt')
with open(file_path, 'r') as file:
...
3.2 使用pathlib(Python 3.4+推薦)
from pathlib import Path
# 創(chuàng)建Path對象
file_path = Path('data/example.txt')
# 檢查文件是否存在
if file_path.exists():
# 讀取文件
content = file_path.read_text(encoding='utf-8')
print(content)
# 寫入文件
file_path.write_text("新內(nèi)容\n", encoding='utf-8')
4. 編碼問題處理
4.1 常見編碼問題
UnicodeDecodeError:通常是因為文件編碼與指定編碼不匹配UnicodeEncodeError:寫入時使用了不支持的字符
4.2 解決方案
# 嘗試常見編碼
encodings = ['utf-8', 'gbk', 'gb2312', 'big5', 'latin1']
def read_with_fallback(filename):
for encoding in encodings:
try:
with open(filename, 'r', encoding=encoding) as file:
return file.read()
except UnicodeDecodeError:
continue
raise UnicodeDecodeError(f"無法解碼文件 {filename},嘗試了所有常見編碼")
# 寫入時忽略無法編碼的字符(不推薦,除非必要)
with open('output.txt', 'w', encoding='utf-8', errors='ignore') as file:
file.write("包含特殊字符的文本")
5. 高級技巧
5.1 同時讀寫文件
使用'r+'模式可以同時讀寫文件:
with open('example.txt', 'r+', encoding='utf-8') as file:
content = file.read()
file.seek(0) # 移動指針到文件開頭
file.write("新內(nèi)容\n" + content) # 在開頭插入內(nèi)容
5.2 CSV格式文本處理
雖然CSV是專門格式,但常以.txt擴展名保存:
import csv
# 寫入CSV格式文本
with open('data.txt', 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['姓名', '年齡', '城市'])
writer.writerow(['張三', 25, '北京'])
writer.writerow(['李四', 30, '上海'])
# 讀取CSV格式文本
with open('data.txt', 'r', encoding='utf-8') as file:
reader = csv.reader(file)
for row in reader:
print(row)
5.3 JSON格式文本處理
對于結構化數(shù)據(jù),JSON是更好的選擇但仍可能保存為.txt:
import json
data = {
"name": "張三",
"age": 25,
"skills": ["Python", "數(shù)據(jù)分析"]
}
# 寫入JSON
with open('data.txt', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
# 讀取JSON
with open('data.txt', 'r', encoding='utf-8') as file:
loaded_data = json.load(file)
print(loaded_data)
6. 最佳實踐
- 始終使用
with語句:確保文件正確關閉 - 明確指定編碼:推薦始終使用UTF-8
- 處理異常:特別是文件不存在或權限問題時
- 避免硬編碼路徑:使用
os.path或pathlib - 大文件處理:使用逐行或分塊讀取
- 路徑分隔符:跨平臺時使用
os.path.join()或pathlib
完整示例
from pathlib import Path
def process_file_operations():
# 創(chuàng)建目錄(如果不存在)
data_dir = Path('data')
data_dir.mkdir(exist_ok=True)
# 寫入文件
file_path = data_dir / 'example.txt'
file_path.write_text(
"第一行文本\n"
"第二行文本\n"
"第三行文本\n",
encoding='utf-8'
)
# 讀取并處理文件
if file_path.exists():
content = file_path.read_text(encoding='utf-8')
print("文件內(nèi)容:")
print(content)
# 追加內(nèi)容
file_path.write_text(
content + "\n這是追加的內(nèi)容\n",
encoding='utf-8'
)
else:
print("文件不存在")
if __name__ == "__main__":
process_file_operations()
結論
Python提供了簡單而強大的工具來處理txt文件的讀寫操作。從基本的文件操作到高級的路徑處理和編碼管理,掌握這些技術可以讓你高效地處理各種文本數(shù)據(jù)場景。對于簡單的任務,內(nèi)置的open()函數(shù)通常就足夠了;對于更復雜的路徑操作或跨平臺需求,pathlib模塊提供了更現(xiàn)代的解決方案。記住始終考慮文件編碼和異常處理,這將使你的代碼更加健壯和可靠。
以上就是Python讀寫txt文件的多種方法的詳細內(nèi)容,更多關于Python讀寫txt文件的資料請關注腳本之家其它相關文章!
相關文章
beam search及pytorch的實現(xiàn)方式
這篇文章主要介紹了beam search及pytorch的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-05-05
Python基于socket模塊實現(xiàn)UDP通信功能示例
這篇文章主要介紹了Python基于socket模塊實現(xiàn)UDP通信功能,結合實例形式分析了Python使用socket模塊實現(xiàn)IPV4協(xié)議下的UDP通信客戶端與服務器端相關操作技巧,需要的朋友可以參考下2018-04-04
Python使用Transformers實現(xiàn)機器翻譯功能
近年來,機器翻譯技術飛速發(fā)展,從傳統(tǒng)的基于規(guī)則的翻譯到統(tǒng)計機器翻譯,再到如今流行的神經(jīng)網(wǎng)絡翻譯模型,尤其是基于Transformer架構的模型,翻譯效果已經(jīng)有了質(zhì)的飛躍,本文將詳細介紹如何使用Transformers庫來實現(xiàn)一個機器翻譯模型,需要的朋友可以參考下2024-11-11

