0

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.

lostSoul
  • 7
  • 2
  • Does this answer your question? [How to append new data onto a new line](https://stackoverflow.com/questions/21839803/how-to-append-new-data-onto-a-new-line) – Yevhen Kuzmovych Dec 06 '22 at 19:16

1 Answers1

0

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
KyIe LiebIer
  • 408
  • 2
  • 12