Python 如何附加到 CSV 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4249185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:55:49  来源:igfitidea点击:

How to append to a CSV file?

pythoncsv

提问by Merlin

Using Python to append CSV file, I get data every other row. How do I fix?

使用 Python 附加 CSV 文件,我每隔一行获取数据。我该如何解决?

import csv

LL = [(1,2),(3,4)]

Fn = ("C:\Test.csv")
w = csv.writer(open(Fn,'a'), dialect='excel')
w.writerows(LL)

C:\test.csvwhen opened looks like this:

C:\test.csv打开后看起来像这样:

1,2

3,4

1,2

3,4

采纳答案by John Machin

Appending is irrelevant to the problem; notice that the first two rows (those from the original file) are also double-spaced.

追加与问题无关;请注意,前两行(来自原始文件的行)也是双倍行距。

The real problem is that you have opened your file in textmode.

真正的问题是您以文本模式打开了文件。

CSV is a binary format, believe it or not. The csv module is writing the misleadingly-named "lineterminator (should be "rowseparator") as \r\nas expected but then the Windows C runtime kicks in and replaces the \nwith \r\nso that you have \r\r\nbetween rows. When you "open" the csv file with Excel it becomes confused

CSV 是一种二进制格式,信不信由你。csv 模块正在\r\n按预期编写具有误导性的名称“lineterminator(应该是“rowseparator”),但随后 Windows C 运行时启动并替换\nwith\r\n以便您\r\r\n在行之间拥有。当您用 Excel“打开”csv 文件时它变得混乱

Always open your CSV files in binary mode ('rb', 'wb', 'ab'), whether you are operating on Windows or not. That way, you will get the expected rowseparator (CR LF) even on *x boxes, your code will be portable, and any linefeeds embedded in your data won't be changed into something else (on writing) or cause dramas (on input, provided of course they're quoted properly).

无论您是否在 Windows 上操作,始终以二进制模式('rb'、'wb'、'ab')打开 CSV 文件。这样,即使在 *x 框上,您也将获得预期的行分隔符 (CR LF),您的代码将是可移植的,并且数据中嵌入的任何换行符都不会更改为其他内容(写入时)或导致戏剧性(输入时) ,当然前提是它们被正确引用)。

Other problems:

其他问题:

(1) Don't put your data in your root directory (C:\). Windows inherited a hierarchical file system from MS-DOS in the 1980s. Use it.

(1) 不要将数据放在根目录 ( C:\) 中。Windows 从 1980 年代的 MS-DOS 继承了分层文件系统。用它。

(2) If you must embed hard-wired filenames in your code, use raw strings r"c:\test.csv"... if you had "c:\test.csv"the '\t' would be interpreted as a TAB character; similar problems with \rand \n

(2) 如果您必须在代码中嵌入硬连线文件名,请使用原始字符串r"c:\test.csv"...如果您有"c:\test.csv"'\t' 将被解释为 TAB 字符;类似的问题\r\n

(3) The examples in the Python manual are aligned more towards brevity than robust code.

(3) Python 手册中的示例更倾向于简洁而不是健壮的代码。

Don't do this:

不要这样做:

w = csv.writer(open('foo.csv', 'wb'))

Do this:

做这个:

f = open('foo.csv', 'wb')
w = csv.writer(f)

Then when you are finished, you have favailable so that you can do f.close()to ensure that your file contents are flushed to disk. Even better: read up on the new withstatement.

然后,当您完成后,您就f可以使用了,以便您可以f.close()确保将文件内容刷新到磁盘。更好的是:阅读新with声明。

回答by kenan bolat

I have encountered a similar problem with appending an already created csv file, while running on windows.

在 Windows 上运行时,我遇到了附加已创建的 csv 文件的类似问题。

As in this case writing and appending in "binary" mode avoids adding extra line to each rows written or appended by using the python script. Therefore;

在这种情况下,以“二进制”模式编写和附加可避免向使用 python 脚本编写或附加的每一行添加额外的行。所以;

w = csv.writer(open(Fn,'ab'),dialect='excel')