gpt4 book ai didi

python - 这是我目前写入文件的方式。但是,我不能做 UTF-8 吗?

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:31 25 4
gpt4 key购买 nike

f = open("go.txt", "w")
f.write(title)
f.close()

如果“title”是 japanese/utf-8 怎么办?如何修改此代码以能够在不出现 ascii 错误的情况下编写“title”?

编辑:那么,我该如何读取这个 UTF-8 格式的文件呢?

最佳答案

How to use UTF-8 :

import codecs

# ...
# title is a unicode string
# ...

f = codecs.open("go.txt", "w", "utf-8")
f.write(title)

# ...

fileObj = codecs.open("go.txt", "r", "utf-8")
u = fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file

关于python - 这是我目前写入文件的方式。但是,我不能做 UTF-8 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2909386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com