天天看點

python io open()寫入中文亂碼問題

python io open()寫入中文亂碼問題:
with open("test.txt", "wt") as out_file
    out_file.write("該文本寫入到檔案中")

with open("test.txt", "rt") as in_file:
    text = in_file.read()

print(text)  # ���ı�д�뵽�ļ���
           
解決寫入中文亂碼問題,在open()中添加encoding = " utf-8 "
with open("test.txt", "wt", encoding= "utf-8") as out_file:
    out_file.write("該文本寫入到檔案中")

with open("test.txt", "rt", encoding="utf-8") as in_file:
    text = in_file.read()

print(text)  # 該文本寫入到檔案中