Python文件寫入和追加內容
1. 基本文件寫入
# 使用write()方法寫入
with open('test.txt', 'w', encoding='utf-8') as file:
file.write('Hello, World!n')
file.write('這是第二行n')
# 使用print()寫入
with open('test.txt', 'w', encoding='utf-8') as file:
print('Hello, World!', file=file)
print('這是第二行', file=file)
# 寫入多行
lines = ['第一行n', '第二行n', '第三行n']
with open('test.txt', 'w', encoding='utf-8') as file:
file.writelines(lines)
2. 追加內容
# 使用追加模式
with open('test.txt', 'a', encoding='utf-8') as file:
file.write('這是追加的內容n')
# 追加多行內容
new_lines = ['追加第一行n', '追加第二行n']
with open('test.txt', 'a', encoding='utf-8') as file:
file.writelines(new_lines)
# 使用print追加
with open('test.txt', 'a', encoding='utf-8') as file:
print('使用print追加的內容', file=file)
3. 格式化寫入
# 使用f-string格式化
name = "小明"
age = 18
with open('info.txt', 'w', encoding='utf-8') as file:
file.write(f'姓名:{name}n年齡:{age}n')
# 使用format()方法
template = "姓名:{}n年齡:{}n"
with open('info.txt', 'w', encoding='utf-8') as file:
file.write(template.format(name, age))
4. 實用示例
# 寫入CSV格式數據
def write_csv(filename, data):
with open(filename, 'w', encoding='utf-8') as file:
for row in data:
line = ','.join(str(item) for item in row)
file.write(line + 'n')
# 日誌記錄器
def log_writer(filename):
def write_log(message):
with open(filename, 'a', encoding='utf-8') as file:
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
file.write(f'[{timestamp}] {message}n')
return write_log
# 使用示例
logger = log_writer('app.log')
logger('應用程序啟動')
logger('執行操作A')
5. 二進制文件寫入
# 寫入二進制數據
with open('data.bin', 'wb') as file:
file.write(b'Hello World')
# 寫入圖片文件
def copy_image(source, destination):
with open(source, 'rb') as src:
with open(destination, 'wb') as dst:
dst.write(src.read())
練習題
-
創建一個簡單的記事本程序:
- 允許用戶輸入多行文本
- 提供保存功能
- 支持追加內容
-
實現一個日誌系統:
- 記錄不同級別的日誌(INFO, WARNING, ERROR)
- 包含時間戳和日誌級別
- 支持日誌文件輪換
常見錯誤和注意事項
- 寫入模式(‘w’)會清空原有內容
- 確保正確的文件編碼
- 注意文件路徑的存在性
- 處理大文件時注意內存使用
- 正確處理換行符
- 適當的錯誤處理
最佳實踐
- 使用with語句自動關閉文件
- 適當的異常處理
- 大文件使用分塊寫入
- 注意文件權限問題
- 定期刷新和備份重要文件