替换字符串中的非UTF8

2024-09-30 01:32:52 发布

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

代码如下:

s = 'Waitematā'
w = open('test.txt','w')
w.write(s)
w.close()

我得到以下错误

UnicodeEncodeError: 'charmap' codec can't encode character '\u0101' in position 8: character maps to <undefined> 字符串将使用宏a,ā打印。但是,我无法将其写入.txt或.csv文件

我能把我们的马克龙a,ā换成没有马克龙吗?提前谢谢你的帮助


Tags: 代码testtxtclose错误opencancodec
2条回答

请注意,如果使用open('text.txt', 'w')打开文件并向其中写入字符串,则不是向文件写入字符串,而是将编码字符串写入文件。所使用的编码取决于LANG环境变量或其他因素

要强制使用UTF-8,正如您在标题中所建议的,您可以尝试以下方法:

w = open('text.txt', 'wb') # note for binary
w.write(s.encode('utf-8')) # convert str into byte explicitly
w.close()

open所述:

In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding.

并非所有编码都支持所有Unicode字符。由于编码在未指定时依赖于平台,因此在读取或写入文本文件时显式地调用编码更好、更便于移植。UTF-8支持所有Unicode代码点:

s = 'Waitematā'
with open('text.txt','w',encoding='utf8') as w:
   w.write(s)

相关问题 更多 >

    热门问题