sathish sathish - 4 months ago 8
Python Question

Replace a column in a csv file using python?

How to replace a column in csv file with a condition in python?

My csv file contains:

34,2016-06-14 13:37:10,,1,,,t
34,2016-06-15 13:48:20,,1,,,f
34,2016-06-16 13:55:34,,1,,,t
34,2016-06-17 13:48:40,,1,,,f
34,2016-06-18 13:41:27,,1,,,t


I want to change the last column. With a condition. That is I want to change "t" to "1" and "f" to "0" using python program.

I have seen many examples but not with this condition and examples are little bit confusing.

I tried a little bit but it is not working. I also don't know it is correct method or not

f = open('/home/rck/Desktop/attendance/month.csv','rb')
fo = open('/home/rck/Desktop/attendance/demo.csv','wb')

for line in f:
bits = line.split(',')

if bits[5] == '"t"':
bits[5] = '"1"'

elif bits[5] == '"f"':
bits[5] = '"0"'
fo.write( ','.join(bits) )

f.close()
fo.close()


How can I achieve this?

Thanks....

Answer

You can use regular expression to do the job:

import re

for line in f:
    line = re.sub('\w$', lambda x: '"1"' if x.group(0) == 't' else '"0"', line)
    fo.write(line)
Comments