如何附加到CSV文件? [英] How to append to a CSV file?

查看:101
本文介绍了如何附加到CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

import csv

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

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

C:\test.csv打开时如下所示:

1,2

3,4

1,2

3,4

推荐答案

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

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

真正的问题是您已以 text 模式打开文件.

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

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

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

无论是否在Windows上运行,始终以二进制模式("rb","wb","ab")打开CSV文件.这样,即使在* x盒子上,您也将获得预期的行分隔符(CR LF),您的代码将是可移植的,并且数据中嵌入的任何换行都不会更改为其他内容(在编写时)或引起戏剧性(在输入时) ,当然,只要引用正确即可.

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).

其他问题:

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

(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.

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

(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 \r and \n

(3)Python手册中的示例更加简洁而不是健壮的代码.

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

不要这样做:

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

执行此操作:

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

然后,完成操作后,便可以使用f,以便可以执行f.close()以确保将文件内容刷新到磁盘上.更好的是:阅读新的with语句.

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

这篇关于如何附加到CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆