编写文本文件Python时出错

时间:2014-04-13 23:17:56

标签: python text fwrite

您好我正在运行程序来解析HTML地址中的表格。一切正常,我能够打印提取的数据。但是当我尝试用数据写一个txt文件时,我得到下面的错误信息。有人可以帮帮我吗?我不知道自己错过了什么。

myfile.write(tds[0].text+ ","+ tds[4].text+ ","+ tds[7].text+ ","+ tds[12].text+ ","+ tds[14].text+ ","+ tds[17].text)

错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "teste.py", line 14, in <module>
    myfile.write(tds[0].text+ ","+ tds[4].text+ ","+ tds[7].text+ ","+ tds[12].text+ ","+ tds[14].text+ ","+ tds[17].text.encode('utf8'))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1: ordinal not in range(128)

2 个答案:

答案 0 :(得分:0)

您正在混合文本类型。你使用&#34;,&#34;以及* .text方法,用于定义希望写入文件的整个字符串。因此,您正在混合编码。虽然您的问题存在更优雅的解决方案,但实现此目的的快速而肮脏的方法可能是使用:

str(tds[*])

tds[*].text()

答案 1 :(得分:0)

要了解代码中断的原因,请查看此anwser about the basics of Python and Unicode

在您的情况下,使用tds[*].text.decode("ecoding of original HTML")

可能会有所帮助
相关问题