-2

我的部分代码如下。我想将终端的输出导出到文本文件中,但出现以下错误:

UnicodeEncodeError  Traceback (most recent call last)
<ipython-input-2-c7d647fa741c> in <module>()
     34     text_file = open("Output.txt", "w")
     35 
---> 36     text_file.write(data)
     37     #print (data)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 150-151: ordinal not in range(128)

# data is multi line text
data = ''.join(soup1.findAll('p', text=True))
text_file = open("Output.txt", "w")
text_file.write(data)
# print (data)
4

1 回答 1

2

在写入文件之前对文本进行编码:

text_file.write(data.encode("utf-8"))
于 2013-09-22T13:38:01.433 回答