无法将 unicode 编码为 python 中的 .txt 文件

Unable to encode a unicode into a .txt file in python

因此,在尝试弄乱 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>

有人可以帮忙吗?

您一开始就以 UTF-8 格式读取输入文件,做得很好。您唯一缺少的是对输出文件做同样的事情:

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