I am trying to put a list of string into csv, but in the output csv each letter is separated by comma. Is there a way to fix this?
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 Answer 1
Printing act shows that you have a list of strings [u'M14422', u'M28900', u'M33698', ...]. writerows treats each string in the list as a row, and that means that each character in the string is a column. That's why you end up with comma-separated characters in the finel csv.
The solution is to put each string into its own list so that the row is a list with a single column.
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])
answered Apr 2, 2016 at 2:39
tdelaney
78k6 gold badges91 silver badges129 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
actvariable and see what it looks like (probably a big blob of text) versus what you think it should look like (a table, a row, a pair of columns, a single paragraph). Then try tosplitordedentor[make a list]or whatever you need to do.actis a string, not a list of strings. Convert it into a list of the strings you want comma-separated first.