0

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)
6
  • Why not just use another seperator then? Like tab or ; Commented Apr 2, 2016 at 1:17
  • then each letter is separated by tab or ; Commented Apr 2, 2016 at 1:20
  • This usually means you are passing a string where the CSV code expects a list. Try printing out your act variable 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 to split or dedent or [make a list] or whatever you need to do. Commented Apr 2, 2016 at 1:26
  • This is because act is a string, not a list of strings. Convert it into a list of the strings you want comma-separated first. Commented Apr 2, 2016 at 1:26
  • 1
    can you post your input sample and expected output? Commented Apr 2, 2016 at 1:40

1 Answer 1

2

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.