Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read and write on same csv file

Tags:

python

csv

I am trying to read and write on the same CSV file:

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 are:

  • 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.

like image 847
laspal Avatar asked Jun 30 '10 04:06

laspal


People also ask

Can you read and write to a CSV file at the same time?

You can do open("data. csv", "rw") , this allows you to read and write at the same time. So will this help me modify the data?

Can you read and write to same CSV file in Python?

You can't open a file in both read and write modes at once. As Jason points out, if your CSV is too big for your memory, then you'll need to write to a different filename and then rename it. This will likely be a bit slower.

How do I open a CSV file for both reading and writing in Python?

Reading from a CSV file is done using the reader object. The CSV file is opened as a text file with Python's built-in open() function, which returns a file object.

What is writer () and Reader () method in CSV file?

Writing CSV files Using csv.The csv. writer() function returns a writer object that converts the user's data into a delimited string. This string can later be used to write into CSV files using the writerow() function.


1 Answers

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.

like image 95
Michał Niklas Avatar answered Sep 20 '22 15:09

Michał Niklas