newbie question: converting csv to another dialect

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Feb 15 07:38:49 EST 2008


Albert-jan Roskam a écrit :
> Hi all,
> 
> I have a csv file with tab as a delimiter. I want to
> convert it into one that is comma delimited. I changed
> the regional settings on my computer to US. 
> 
> At first I thought I could use the CSV module for
> this, by reading the csv file, registering the new
> (desired = comma-delimited) dialect, and writing it.

That's what I'd do indeed.

> Another option (which may be easier)

Hum... Depends on the effective csv dialect used. So-called csv files 
are not necessarily trivial to handle properly.

> I tried was:
> f = open('d:/temp/myfile.csv', ' rw')
> for row in f:
>     row.replace("\t",",")


> Which is a start, but doesn't do the entire job. 

// without proper error handling
source = '/path/to/source.csv'
dest = source + '.new'

fin = open(source, 'r')
fout = open(dest, 'w')

for row in source:
   // let's hope there's no ',' anywhere in source...
   fout.write(row.replace("\t", ","))

fin.close()
fout.close()
os.rename(dest, source)

> Could somebody help me with this please?

yes : forget the above code and use the csv module.

HTH



More information about the Python-list mailing list