繁体   English   中英

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

[英]Appending at new line in Python using csv library

我无法处理用户忘记换行的情况。

我正在尝试使用以下代码将 append 换行到 python 中的 csv 文件 -

with open(local_file_location, 'a') as file:
    writer = csv.writer(file)
    writer.writerow(row)

但是如果文件没有新行,它只是第一次附加到同一行的最后一行。 我不确定如何处理。

Ex- 输入-

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

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

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

但我希望在此事件中处理 output 如下所示 -

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

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

让我知道我能做什么。

您可以检查文件是否换行符结尾。

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