I want to append to a new row in my CSV file when i write to it. Current CSV file look like this:
a,b,c
1,1,1
my code to append to CSV file:
with open('mycsvfile.csv','a') as f:
writer=csv.writer(f)
writer.writerow(['0','0','0'])
new mycsvfile:
a,b,c
1,1,1,0,0,0
What i want:
a,b,c
1,1,1
0,0,0
If you need to append row(s) to a CSV file, replace the write mode ( w ) with append mode ( a ) and skip writing the column names as a row ( writer. writerow(column_name) ).
For appending a new row to an existing CSV file we have many ways to do that. Here we will discuss 2 ways to perform this task effectively. So, we have 2 ways first is 'Append a list as a new row to the existing CSV file' and the second way is 'Append a dictionary as a new row to the existing CSV file'.
You cannot overwrite a single row in the CSV file. You'll have to write all the rows you want to a new file and then rename it back to the original file name.
The problem is your original file didn't have a final newline written to it. this reproduces the problem:
#!python3
import csv
#initial content
with open('mycsvfile.csv','w') as f:
f.write('a,b,c\n1,1,1') # NO TRAILING NEWLINE
with open('mycsvfile.csv','a',newline='') as f:
writer=csv.writer(f)
writer.writerow([0,0,0])
writer.writerow([0,0,0])
writer.writerow([0,0,0])
with open('mycsvfile.csv') as f:
print(f.read())
Output:
a,b,c
1,1,10,0,0
0,0,0
0,0,0
Just make sure the original file was generated properly:
#!python3
import csv
#initial content
with open('mycsvfile.csv','w') as f:
f.write('a,b,c\n1,1,1\n') # TRAILING NEWLINE
with open('mycsvfile.csv','a',newline='') as f:
writer=csv.writer(f)
writer.writerow([0,0,0])
writer.writerow([0,0,0])
writer.writerow([0,0,0])
with open('mycsvfile.csv') as f:
print(f.read())
Output:
a,b,c
1,1,1
0,0,0
0,0,0
0,0,0
You can do some hack to seek to the end of the file and decide to write the extra newline, but better to fix the existing file generation so it always writes newlines. The easiest way to do that is use the csv
module from the start, since it will always add a newline with writerow
.
With some tinkering I realized you can add the following line to make sure you begin writing on a new line in a csv. Though it seems kind of hackish. Documentation mentions a lot about a kwarg newline='', but it wasn't recognized as valid.
writer.writerow([])
I also open with 'ab' parameter.
import csv
with open('mycsvfile.csv','ab') as f:
writer=csv.writer(f)
writer.writerow([])
writer.writerow(['0','0','0'])
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