[Tutor] writing csv files
Peter Otten
__peter__ at web.de
Sat May 22 10:48:25 CEST 2010
prasad rao wrote:
> hello!
>
> I got a problem writing csv file.
>
> 1)
> csvw=csv.writer(open('/home/prasad/kkm','w'),
> dialect='excel',fieldnames=names)
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: 'fieldnames' is an invalid keyword argument for this function
>
> 2)
> for x in csvr:
> ... y=lambda x: ''.join([x.split()[3],x.split()[-3],x.split()[-6]])
> ... csvw.write(y)
> ...
> Traceback (most recent call last):
> File "<stdin>", line 3, in <module>
> AttributeError: '_csv.writer' object has no attribute 'write'
>
> At http://www.python.org/dev/peps/pep-0305/ they are using the function
> write
> and the argument fieldnames.
>
> Where is the problem?Please someone show me a way to do it.
The PEP is not uptodate. If you are using Python 2.6 have a look at
http://docs.python.org/library/csv.html
You can find the documentation for other versions of Python via
http://docs.python.org/index.html
If you are using 2.6 the following might work:
# prepare rows
rows = (row.split() for row in csvr)
rows = ((row[3], row[-3], row[-6]) for row in rows)
with open(filename, "wb") as out:
w = csv.writer(out, dialect="excel")
w.writerow(names) # write header
w.writerows(rows) # write data
Peter
More information about the Tutor
mailing list