繁体   English   中英

Python:在csv文件中追加一行会导致它被随机拆分

[英]Python: appending a row in a csv file cause it to be split randomly

我正在编写一个python(3.7)函数,它接受一个字符串并将其附加到.csv文件中。 这是代码:

def write_to_file(row):
    print("row: ",[row])
    with open('output.csv', mode='a') as output_file:
        output_file_writer = csv.writer(output_file)
        output_file_writer.writerow([row])

当我打印行时,我得到的结果如下:

row:  ["Introducing company, the tool that let's you manage your coins alt-coin on coinbase-pro, and many other exchanges automatically."]

但它写的.csv看起来像这样: 在此输入图像描述

有趣的是,如果我复制打印输出并在write命令中对其进行硬编码,如下所示:

                output_file_writer.writerow(["Introducing company, the tool that let's you manage your coins alt-coin on coinbase-pro, and many other exchanges automatically."])

.csv文件是正确的。 我错过了什么?

尝试在open()中使用newline ='',即with open('output.csv', mode='a', newline='') as output_file:

引自python docs

如果未指定newline ='',则不会正确解释嵌入在引用字段中的换行符,并且在写入时使用\\ r \\ n linendings的平台上将添加额外的\\ r \\ n。 指定newline =''应始终是安全的,因为csv模块执行自己的(通用)换行处理。

暂无
暂无

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

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