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

时间:2019-05-14 23:45:28

标签: python csv

我正在编写一个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看起来像这样: enter image description here

有趣的是,如果我复制打印输出并在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文件正确。我想念什么?

1 个答案:

答案 0 :(得分:0)

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

引自python docs

  

如果未指定换行符='',则将换行符嵌入带引号的字段中   在使用\ r \ n的平台上将无法正确解释   linendings写一个额外的\ r将被添加。应该总是   安全指定newline ='',因为csv模块会自己执行   (通用)换行符处理。