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.
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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With