编写时出现python编码问题

2024-09-27 07:30:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python3并用python写入rtf文件,但是在使用charø(也称为“\u00f8”)时出现了一些编码问题。 代码如下:

>>> myText = "a \u00f8 b"
>>> myText
'a ø b'

>>> out_file = open('test.rtf', 'w', encoding='utf8')
>>> textForFile = "{\\rtf1\\utf8 " + myText + "}"

>>> out_file.write(textForFile)
18
>>> out_file.close()

文件测试.rtf现在包括以下文本:

a ˆ‚ b

而不是:

'a ø b'

你知道我在编码上遗漏了什么吗?你知道吗


Tags: 文件代码test编码openutf8outpython3
1条回答
网友
1楼 · 发布于 2024-09-27 07:30:26

解决这个问题的关键是用cp1252对python文件进行编码,并在rtf代码中使用ansicpg1252。我找到了ansicpg1252的想法in this documentation。现在TextEdit、LibreOffice和OpenOffice都能正确地打开文件。你知道吗

正确代码:

>>> myText = "a \u00f8 b"
>>> myText
'a ø b'
>>> out_file = open('test.rtf', 'w', encoding='cp1252')
>>> textForFile = "{\\rtf1\\ansicpg1252" + myText + "}"
>>> out_file.write(textForFile)
>>> out_file.close()

相关问题 更多 >

    热门问题