使用python将字符串列表写入csv

时间:2016-04-02 01:15:17

标签: python csv

我正在尝试将字符串列表放入csv,但在输出csv中,每个字母用逗号分隔。有办法解决这个问题吗?

from urllib2 import urlopen    
import csv
from scrapy.selector import Selector
def make_soup(url):
    data_text = urlopen(url).read()
    hxs = Selector(text=data_text)
    return hxs

hxs = make_soup("http://propinfo.co.lincoln.or.us/property-search?search=+NW+3RD+ST")
act = hxs.xpath('//*[@id="block-system-main"]/div[2]/div/div[2]/table/tbody/tr/td/a/text()').extract()



with open("accounts.csv", "wb") as f1:
    writer = csv.writer(f1)
    writer.writerows(act)

1 个答案:

答案 0 :(得分:2)

打印act表示您有一个字符串列表[u'M14422', u'M28900', u'M33698', ...]writerows将列表中的每个字符串视为一行,这意味着字符串中的每个字符都是一列。这就是为什么你最终在精细csv中使用逗号分隔的字符。

解决方案是将每个字符串放入自己的列表中,以便该行是一个包含单个列的列表。

from urllib2 import urlopen
import csv
from scrapy.selector import Selector
def make_soup(url):
    data_text = urlopen(url).read()
    hxs = Selector(text=data_text)
    return hxs

hxs = make_soup("http://propinfo.co.lincoln.or.us/property-search?search=+NW+3RD+ST")
act = hxs.xpath('//*[@id="block-system-main"]/div[2]/div/div[2]/table/tbody/tr/td/a/text()')

with open("accounts.csv", "wb") as f1:
    writer = csv.writer(f1)
    for row in act:
        writer.writerow([row])