Appending at new line in Python using csv library
Problem Description:
I am unable to handle case where user forgot to put newline.
I am trying to append new line to a csv file in python using below code –
with open(local_file_location, 'a') as file:
writer = csv.writer(file)
writer.writerow(row)
But in case if file do not have a new line it simply appends to same last line for the first time. And I am not sure how to handle that.
Ex-
Input-
1,2,3,4 <no-newline>
add row – {a,b,c,d}
Output-
1,2,3,4,a,b,c,d
but I want handle output in this event case to be as below –
1,2,3,4
a,b,c,d
Note: it should just append as well in case user file already have a new line.-> which current program does perfectly.
Let me know what can I do.
Solution – 1
You can check if a file ends with a newline.
with open(local_file_location, 'r') as file:
data = file.read()
if data.endswith('n'):
# some logic