UnicodeDecodeError将编码添加到自定义函数输入

2024-05-05 00:13:50 发布

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

你能告诉我我现在的思维方式哪里出了问题吗?这是我的职责:

def replace_line(file_name, line_num, text):
  lines = open(f"realfolder/files/{item}.html", "r").readlines()
  lines[line_num] = text
  out = open(file_name, 'w')
  out.writelines(lines)
  out.close()

这是一个被称为:

replace_line(f'./files/{item}.html', 9, f'text {item} wordswordswords' + '\n')

我需要将文本输入编码为utf-8。我不知道为什么我还不能做到这一点。我还需要保留fstring值

我一直在做一些事情,比如添加:

str.encode(text)
#or
text.encode(encoding = 'utf-8')

到“替换行”功能的顶部。这没用。我尝试了几十种不同的方法,但每种方法都会给我留下这个错误

UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2982: character maps to undefined


1条回答
网友
1楼 · 发布于 2024-05-05 00:13:50

您需要将编码设置为utf-8,以便打开要读取的文件

lines = open(f"realfolder/files/{item}.html", "r", encoding="utf-8").readlines()

并打开要写入的文件

out = open(file_name, 'w', encoding="utf-8")

相关问题 更多 >