我有一些我从网站上提取的数据。这是我用来抓住它的代码(我的实际代码要长得多,但我认为这总结了它)。
lid_restrict_save = []
for t in range(10000,10020):
address = 'http://www.tspc.oregon.gov/lookup_application/' + lines2[t]
page = requests.get(address)
tree = html.fromstring(page.text)
#District Restriction
dist_restrict = tree.xpath('//tr[11]//text()')
if u"District Restriction" in dist_restrict:
lid_restrict_save.append(id2)
我正在尝试导出此列表:
print lid_restrict_save
[['5656966VP65', '5656966RR68', '56569659965', '56569658964']]
到文本文件。
f = open('dis_restrict_no_uniqDOB2.txt', 'r+')
for j in range(0,len(lid_restrict_save)):
s = ( (unicode(lid_restrict_save[j]).encode('utf-8') + ' \n' ))
f.write(s)
f.close()
我希望文字看起来像这样:
5656966VP65
5656966RR68
56569659965
56569658964
此代码有效但仅在我从0开始range
时
f = open('dis_restrict.txt', 'r+')
for j in range(0,len(ldob_restrict)):
f.write( ldob_restrict[j].encode("utf-8") + ' \n' )
f.close()
当我尝试更改代码时,我不断收到此错误:
"AttributeError: 'list' object has no attribute 'encode'."
如果有人有任何提示,将不胜感激。
答案 0 :(得分:0)
lid_restrict_save
是一个嵌套列表,因此您无法对第一个元素进行编码,因为它不是字符串。
您可以使用以下方法写入txt文件:
lid_restrict_save = [['5656966VP65', '5656966RR68', '56569659965', '56569658964']]
lid_restrict_save = lid_restrict_save[0] # remove the outer list
with open('dis_restrict.txt', 'r+') as f:
for i in lid_restrict_save:
f.write(str(i) + '\n')