csv模块自动写入不需要的回车

当使用pythons csv模块创build一个csv时,它会自动将回车字符放在string末尾,如果string里面有一个逗号,例如:

['this one will have a carriage return, at the end','this one wont'] 

在一个Excel表中,这将变成:

  | |this on| 

由于额外的回车,它也将包围双引号中的逗号,如预期的string。

我使用的代码是:

 with open(oldfile, 'w', newline='') as csvfile: writer = csv.writer(csvfile) for row in data: writer.writerow(row) 

如何创build一个csv使用相同的数据格式,如果string里面有逗号,将不会有回车,虽然我不介意被双引号包围的string

以下是输出.csv的诊断问题的链接:

导入使用csv模块创build的文件时,Excel显示空单元格

这是被接受的答案。

我已经将我的代码更改为:

 with open(oldfile, 'w', newline='', quoting=csv.QUOTE_MINIMAL) as csvfile: writer = csv.writer(csvfile) for row in data: writer.writerow(row) 

我现在得到的错误:

 TypeError: 'quoting' is an invalid keyword argument for this function 

Python的内置CSV模块有以下选项: csv.QUOTE_MINIMAL 。 当此选项作为参数添加到作者时,它将在给定string中包含引号: "your text, with comma", "other field" 。 这将消除回车的需要。 代码是:

 with open(oldfile, 'w') as csvfile: writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL) for row in data: writer.writerow(row)