【问题标题】:Python: appending a row in a csv file cause it to be split randomlyPython:在 csv 文件中附加一行会导致它被随机拆分
【发布时间】:2019-05-14 23:45:28
【问题描述】:

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

有趣的是,如果我复制 print 的输出并将其硬编码到 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 文件是正确的。我错过了什么?

【问题讨论】:

  • 代码正确。您用来打开 csv 文件的工具是什么?请尝试在原版编辑器中打开它。
  • 你是对的,在数字上文件看起来很乱,但在 Excel 上它看起来应该如此!谢谢!

标签: python csv


【解决方案1】:

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

引用自 python docs:

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

【讨论】:

  • 感谢您的提示,问题出在数字上,在 Excel 上文件看起来很好!
猜你喜欢
  • 2017-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-06
  • 2016-05-23
  • 2013-11-23
相关资源
最近更新 更多