I'll cut the chase, I found a code which "Overwriting a specific row in a csv file using Python's CSV module"
import csv
bottle_list = []
# Read all data from the csv file.
with open('a.csv', 'rb') as b:
bottles = csv.reader(b)
bottle_list.extend(bottles)
# data to override in the format {line_num_to_override:data_to_write}.
line_to_override = {1:['e', 'c', 'd'] }
# Write data to the csv file and replace the lines in the line_to_override dict.
with open('a.csv', 'wb') as b:
writer = csv.writer(b)
for line, row in enumerate(bottle_list):
data = line_to_override.get(line, row)
writer.writerow(data)
But for whatever reason I can't succeed to run it as I'm encountering error in line 8
_csv.Error: iterator should return strings, not bytes (the file should be opened in text mode)
I tried changing the open mode from rb
to rt
to read it as text mode, but second errors popups in line 18
TypeError: a bytes-like object is required, not 'str'
Changing both open modes from rb
to rt
and wb
to wt
fixed both errors, but the result of the csv files contains empty spaces between rows.
I saw a answered question about this. Link
The csv.writer writes \r\n into the file directly. If you don't open the file in binary mode, it will write \r\r\n because on Windows text mode will translate each \n into \r\n.
Any tips on how to overcome this? I've been wondering around answers for quite too long. Thank you