Reputation: 3
I am a newbie to python and have been facing issues with .csv file editing with python 2.5.1 version.
My aim is to replace all ',' with '.' in the csv data.
here is how far i could get.
import csv
import re
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
f_dic = {',':'.'}
with open('file.csv','r') as f:
text=f.read()
with open('file+.csv','w') as w:
text=replace_all(text,f_dic)
print text
w.write(text)
when i run it shows - with 'open' as invalid syntax.
Any Help is appreciated.
Upvotes: 0
Views: 373
Reputation: 90037
To address your syntax error, in Python 2.5, you need:
from __future__ import with_statement
to use the with
statement. It's only available by default in Python 2.6 and later.
Note that you don't use the csv
and re
modules that you import. re
is unnecessary, but if you care about quoting and escaping, you probably want to read the file with the normal defaults for a csv reader and write with the delimiter '.' instead of simply replacing things. Your code as written will only work if there are no .
s in your existing data, and no escaped or quoted ,
s that shouldn't be converted. Depending on how you're going to use the file, naming it "something.csv" may also be a Bad Idea since it's no longer actual comma-separated data.
Upvotes: 4
Reputation: 1508
It looks like you're trying to change the delimiter from comma to period. If this is the case then no need to open as csv, simply open as text and replace all the ','
with open('file.csv', w) as fp:
text = f.read()
text.replace(',' , '.')
fp.tell(0);
fp.write(text)
Upvotes: 0