简体   繁体   中英

Appending at new line in Python using csv library

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM