用Python 3 & unicode写在文件中。

问题描述 投票:6回答:2

这是我的代码。

import codecs
filename = "worst.txt"
file = open(filename, "r",encoding='utf-8')
lines = file.readlines()
texte = ""
for line in lines:
    print(line)
    texte += line
file.close()
print(texte)
texte = texte.split(";")
print(texte)
filename = "oudean.html"



file = open(filename, "w",encoding='utf-8')



file.write("<html><body>\r\n")
for t in texte :
        print(t)
        file.write("""<img src="ouedan.jpg"><br>\r\n""")
        file.write("""Une déclaration à faire ?<br>Besoin d'encouragements?<br>Notre brigade d'élite beat agent est là pour vous aider.<br>Faites appel à nous en appelant le  06 et nous accourrons vous encourager dans l'instant.<br>N hésitez pas.<br>Et pour vous aider durant cette soirée, voilà une accroche a tester, succès garanti :<br>%s<br><br><br><br><br><br><br><br>"""%t)
file.write("</body></html>\r\n")
file.close()

但我给我。

Une déclaration à faire ? Besoin d'encouragements? Notre brigade d'élite beat agent est là pour vous aider. Faites appel à nous en appelant le 06 et nous accourrons vous encourager dans l'instant. N hésitez pas. Et pour vous aider durant cette soirée, voilà une accroche a tester, succès garanti :

那么如何在一个文件中写入unicode字符串呢?

file unicode python-3.x encode
2个回答
10
投票

你的症状看起来像普通的 "UTF-8作为拉丁-1 "的问题。

你有没有检查过你查看文件的软件使用的是什么编码?我想说,问题不一定出在你的python代码上,而是出在查看器上。

如果你用你的示例文本创建一个文件 Une déclaration à faire... 使用UTF-8编码读取该文件,然后使用ISO-8859-1或windows-1252编码读取该文件的内容,那么结果就会显示为你所描述的输出。Une déclaration à faire....

另外,在python 3中,默认的源码是UTF-8。http:/www.python.orgdevpepspep-3120


0
投票

似乎 python 不明白你的源代码是用什么编码的,你必须告诉它,通过使用字节顺序标记(首选)或通过在第一行或第二行用特殊注释声明类型。你必须告诉它,要么使用字节序标记(首选),要么通过在第一行或第二行用特殊注释声明类型。所以,你可以这样做

  1. 告诉你的编辑器在源代码中存储字节顺序标记,或者,如果它不能这样做的话
  2. 开头註明 encoding: utf-8.
© www.soinside.com 2019 - 2024. All rights reserved.