首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 寫入中英文字串至檔案:正確處理編碼

     編輯:更多程式設計知識

Python 3 開檔預設使用平台編碼(Windows 為 cp950/utf-8,Linux 為 utf-8),直接寫入 Unicode 字串通常無問題。但為確保跨平台相容,建議明確指定 encoding='utf-8'。本文示範正確寫法與常見錯誤。

正確寫法 (Python 3)


# -*- coding: utf-8 -*-
content = '你好,腳本之家 .net'

with open('c:/1.txt', 'w', encoding='utf-8') as f:
    f.write(content)

Python 2 相容寫法

Python 2 需使用 codecs 模組或 io.open:


# -*- coding: utf-8 -*-
import codecs
content = u'你好,腳本之家 .net'

with codecs.open('c:/1.txt', 'w', 'utf-8') as f:
    f.write(content)

常見錯誤

  1. 未指定 encoding,Windows 下預設 cp950 導致中文亂碼或 UnicodeEncodeError。
  2. 混用位元組字串與 Unicode 字串(Python 2)。
  3. 讀取時未指定相同 encoding 導致解碼錯誤。

最佳實踐

  • 檔案頂部宣告 # -*- coding: utf-8 -*-。
  • 所有開檔操作明確指定 encoding='utf-8'(或 'utf-8-sig' 含 BOM)。
  • 使用 with 區塊確保檔案正確關閉。
  • 專案統一使用 UTF-8 編碼儲存原始碼與資料檔。

進階:處理大量資料


# 分塊寫入大字串
with open('large.txt', 'w', encoding='utf-8') as f:
    for chunk in generate_chunks():
        f.write(chunk)

正確處理編碼是 Python 處理中文資料的基礎技能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved