【问题标题】:UnicodeDecodeError - Add encoding to custom function inputUnicodeDecodeError - 将编码添加到自定义函数输入
【发布时间】:2021-04-09 01:13:46
【问题描述】:

你能告诉我我目前的思维方式哪里出了问题吗?这是我的功能:

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”编解码器无法解码位置 2982 中的字节 0x90:字符映射到 未定义

【问题讨论】:

    标签: python python-3.x unicode utf-8 encode


    【解决方案1】:

    您需要将编码设置为 utf-8 才能打开要读取的文件

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

    并打开要写入的文件

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

    【讨论】:

      猜你喜欢
      • 2017-03-14
      • 2010-10-31
      • 2021-07-23
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多