Why does csvwriter.writerow () place a comma after each character?

This code opens the URL and adds /names to the end and opens the page and prints a line in test1.csv :

 import urllib2 import re import csv url = ("http://www.example.com") bios = [u'/name1', u'/name2', u'/name3'] csvwriter = csv.writer(open("/test1.csv", "a")) for l in bios: OpenThisLink = url + l response = urllib2.urlopen(OpenThisLink) html = response.read() item = re.search('(JD)(.*?)(\d+)', html) if item: JD = item.group() csvwriter.writerow(JD) else: NoJD = "NoJD" csvwriter.writerow(NoJD) 

But I get this result:

J,D,",", ,C,o,l,u,m,b,i,a, ,L,a,w, ,S,c,h,o,o,l,....

If I change the line to ("JD", "Columbia Law School" ....), then I get

JD, Columbia Law School...)

I could not find in the documentation how to specify a delimeter.

If I try to use delimenter , I get this error:

 TypeError: 'delimeter' is an invalid keyword argument for this function 

Thanks for the help.

+54
python csv
Nov 29 '09 at 21:45
source share
3 answers

It expects a sequence (for example: list or tuple) of rows. You give it one line. A string is also a sequence of strings, but it is a sequence of 1 character string, which is not what you want.

If you only need one line per line, you can do something like this:

 csvwriter.writerow([JD]) 

This carries a JD (string) with a list.

+82
Nov 29 '09 at 21:50
source share

The csv.writer class accepts iterability as an argument to writerow; since strings in Python are iterable in nature, they are an acceptable argument for writerow, but you get the above output.

To fix this, you can break the value based on spaces (I assume you want)

 csvwriter.writerow(JD.split()) 
+5
Nov 29 '09 at 21:53
source share

This happens because when the group () method of the MatchObject instance returns only one value, it returns it as a string. When there are multiple values, they are returned as a tuple of strings.

If you write a string, I think csv.writer iterates over the object you pass to it. If you pass a single line (which is iterable), it iterates over its characters, creating the result you are observing. If you pass a tuple of strings, it gets the actual string, not one character in each iteration.

+1
Nov 29 '09 at 21:52
source share



All Articles