【发布时间】:2020-09-08 10:39:35
【问题描述】:
将字符串写入文件时出现错误:
'charmap' codec can't encode character '\ufb01' in position 108: character maps to <undefined>
这是我尝试过的:
import re
file = open(filepath, "w")
temp_con = content
content = re.sub(r'\W+ \.', '', temp_con)
print(content)
file.write(content)
打印出来的字符串是:
By noon they will all be at my new
house in the Victor's Village. The
reporters, the camera crews, even Effie
Trinket, my old escort, will have made
their way to District 12 from the Capitol.
I wonder if Effie will still be wearing that
silly pink wig, or if she'll be sporting
some other unnatural colour especially
for the Victory Tour. There will be others
waiting, too. A staff to cater to my every
need on the long train trip. A prep team
to beautify me for public appearances.
My stylist and friend, Cinna, who
designed the gorgeous outfits that first
made the audience take notice of me in
the Hunger Games.
If it were up to me, I would try to
forget the Hunger Games entirely. Never
speak of them. Pretend they were
我该如何解决这个问题?
注意:我尝试了这个问题的建议,但结果证明这是 python 2 的解决方案。
【问题讨论】:
-
问题与我链接的副本相同,但反过来:由于您是在写入而不是读取,因此您需要从字符串编码为字节,而不是从字节解码为字符串。
-
奇怪的是它引用了一个宽字符字节码序列。如果这是默认值,即使没有代理,宽字符也已被识别为 BMP 编码。创建并读取包含这些字符的文件龟???㮝䀘䀹?,\uFACE - \uFAD5。即使你用 utf-8 打开它,如果字符在 bmp 中,2 字节的默认编码应该已经成功解码它。如果没有,那将是一个错误。
标签: python python-3.x regex file encoding