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

问题描述

因此,在尝试使用 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")