Appending at new line in Python using csv library

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)

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.


1,2,3,4 <no-newline>

add row – {a,b,c,d}


but I want handle output in this event case to be as below –


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 =

if data.endswith('n'):
    # some logic
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.