tags:

views:

42

answers:

2

Hi, I am trying to read and write on the same csv file. code:

file1 = open(file.csv, 'rb')
file2 = open(file.csv, 'wb')
reader = csv.reader(file1)
writer = csv.writer(file2)
for row in reader:
   if row[2] == 'Test':
      writer.writerow( row[0], row[1], 'Somevalue')

my csv files is val1,2323, Notest val2, 2323, Test

So basically if my row[2] value is Test I want to replace it with 'Some new value' The above code gives me empty csv files.

Thanks

A: 

You should use different output file name. Even if you want the name to be the same, you should use some temporary name and finally rename file.

When you open file in 'w' (or 'wb') mode this file is "cleared" -- whole file content disappears. Python documentation for open() says:

... 'w' for only writing (an existing file with the same name will be erased), ...

So your file is erased before csv functions start parsing it.

Michał Niklas
Oh ok. That may sense. thanks
laspal
A: 

If your csv file is not big enough(to explode the memory), read it all into memory and close the file before open it in write mode.

Or you should consider writing to a new file rather than the same one.

Jason