I am trying to replace multiple strings in a csv file. There is no specific column these strings may be in.
I used the example in this thread Python replace multiple strings, the wordpress entry. I thought I had it with the CSV module but I guess that does not have a replace function. I tried the below, but it only does the replace from the first dictionary. It has to do the entries in the first dictionary first, the order of the second dictionary doesn't matter as much.
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
f_dic = {'-':' '}
s_dic = {' ':' ',' ':' ','SASD D':'SASD-D','DC W':'DC-W',r'PROD\s\d':r'PROD\d'}
with open('file1.csv','r') as f:
text=f.read()
with open('file2.csv','w') as w:
text=replace_all(text,f_dic)
text=replace_all(text,s_dic)
w.write(text)
Can someone help me with this? or even better a csv module version of this?
Thanks, B0T
EDIT
This is my final code after the answer. It worked.
import re
def replace_all(text, dic):
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
f_dic = {'-':' '}
s_dic = {' ':' ',' ':' ','SASD D':'SASD-D','DC W':'DC-W'}
t_dic = {' ':' '}
with open('file1.csv','r') as f:
text=f.read()
text=replace_all(text,f_dic)
text=replace_all(text,s_dic)
text=replace_all(text,t_dic)
text=re.sub(r'PROD\s(?=[1-9])',r'PROD',text)
with open('file2.csv','w') as w:
w.write(text)