gpt4 book ai didi

python - 写入 .txt 文件(UTF-8),python

转载 作者:太空狗 更新时间:2023-10-29 19:32:32 24 4
gpt4 key购买 nike

我想将输出(内容)保存到一个文件中(以 UTF-8 格式保存)。该文件不应该被覆盖,它应该被保存为一个新文件 - 例如文件2.txt所以,我打开一个 file.txt,用 UTF-8 编码,做一些事情然后想把它保存到 UTF-8 的 file2.txt。我该怎么做?

import codecs
def openfile(filename):
with codecs.open(filename, encoding="UTF-8") as F:
contents = F.read()
...

最佳答案

捷径:

file('file2.txt','w').write( file('file.txt').read().encode('utf-8') )

漫漫长路:

data = file('file.txt').read()
... process data ...
data = data.encode('utf-8')
file('file2.txt','w').write( data )

并明确使用“编解码器”:

codecs.getwriter('utf-8')(file('/tmp/bla3','w')).write(data)

关于python - 写入 .txt 文件(UTF-8),python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4112894/

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