【问题标题】:Unable to encode a unicode into a .txt file in python无法在 python 中将 unicode 编码为 .txt 文件
【发布时间】:2021-06-06 23:36:55
【问题描述】:

因此,在尝试使用 python 时,我尝试制作一个程序,该程序可以从 pastebin url 中获取内容,然后将每个内容保存到自己的文件中。我遇到了错误

这是代码:-

import requests
file = open("file.txt", "r", encoding="utf-8").readlines()
for line in file:
  link = line.rstrip("\n")
  n_link = link.replace("https://pastebin.com/", "https://pastebin.com/raw/")
  pastebin = n_link.replace("https://pastebin.com/raw/", "")
  r = requests.get(n_link, timeout=3)
  x = open(f"{pastebin}.txt", "a+")
  x.write(r.text)
  x.close

我收到以下错误:-

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\Py\Misc. Scripts\ai.py", line 9, in <module>
    x.write(r.text)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python39\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2694' in position 9721: character maps to <undefined>

有人可以帮忙吗?

【问题讨论】:

  • 尝试将 x = open(f"{pastebin}.txt", "a+") 更改为 x = open(f"{pastebin}.txt", "a+", encoding="utf- 8")

标签: python python-3.x python-requests pastebin


【解决方案1】:

您在一开始就将输入文件以 UTF-8 格式读取,这样就做得很好。您唯一缺少的就是对输出文件执行相同的操作:

x = open(f"{pastebin}.txt", "a+", encoding="utf-8")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多