使用python附加CSV文件 [英] Using python to append CSV files

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

问题描述

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

  import csv 

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

Fn =(C:\Test.csv)
w = csv.writer(open(Fn,'a'),dialect ='excel')
w。打开时,查看这个:

>

1,2



3,4



2



3,4

解决方案

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



真正的问题是,您已在 > text 模式。



CSV是一种二进制格式, csv模块正如所预期的那样将误导性名称为lineterminator(should berowseparator)的代码写为 \r\\\
,然后Windows C运行时启动并替换 \\\
\r\\\
,以便您拥有 \r当您用Excel打开csv文件时会变得混乱



始终打开您的CSV文件二进制模式('rb','wb','ab'),无论你是在Windows上操作,这样,你会得到预期的行分隔符(CR LF)并且嵌入在您的数据中的任何换行符都不会改变为其他内容(在写作时)或引起戏剧(在输入时,当然是正确引用的)。



其他问题:



(1)不要将你的数据放在根目录下( C:\ )。Windows在20世纪80年代从MS-DOS继承一个分级文件系统。



(2)如果你必须在你的代码中嵌入硬连线的文件名,原始字符串 rc:\test.csv ...如果你有c:\test.csv'\t'将被解释为一个TAB字符;与 \r \\\

相似的问题



不要这样做:

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

这样做:

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

f 可用,以便您可以 f.close(),以确保您的文件内容刷新到磁盘。更好:使用 c>语句读取新的


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" when opened looks this:

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.

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

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

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

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.

(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) The examples in the Python manual are aligned more towards brevity than robust code.

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

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

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