如何使用python在文本文件中编写终端

时间:2013-09-22 13:31:49

标签: python

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

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)

1 个答案:

答案 0 :(得分:2)

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

text_file.write(data.encode("utf-8"))