简体   繁体   English

使用 csv 库追加到 Python 中的新行

[英]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 -我正在尝试使用以下代码将 append 换行到 python 中的 csv 文件 -

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- Ex- 输入-

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

add row - {a,b,c,d} Output-添加行 - {a,b,c,d} 输出 -

1,2,3,4,a,b,c,d

but I want handle output in this event case to be as below -但我希望在此事件中处理 output 如下所示 -

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.注意:它也应该只是 append,以防用户文件已经有一个新行。-> 当前程序完美运行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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