文档章节

python csv学习

chuang_py
 chuang_py
发布于 2015/06/15 20:01
字数 1464
阅读 594
收藏 3

13.1. csvCSV File Reading and Writing

       The so-called CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases.  There is no “CSV standard”, so the format is operationally defined by the many applications which read and write it.  The lack of a standard means that subtle differences often exist in the data produced and consumed by different applications.  These differences can make it annoying to process CSV files from multiple sources.  Still, while the delimiters and quoting characters vary, the overall format is similar enough that it is possible to write a single module which can efficiently manipulate such data, hiding the details of reading and writing the data from the programmer.

        所谓CSV(逗号分隔值)格式是电子表格和数据库中最常见的导入和导出格式。这里没有“CSV 标准”,所以格式是由许多读写它的应用操作上定义。这标准上的缺乏意味着细微的差别往往存在于不同的应用程序生产和消费数据。这些差异可以使多个来源的处理CSV文件变得困难。同时,分隔符和引用字符的变化,整体格式如此相似以至于程序员可以写一个单独的模块,此模块可以有效操纵这样的数据,并且封装读写数据的细节。

       The csv module implements classes to read and write tabular data in CSVformat.  It allows programmers to say, “write this data in the format preferred by Excel,” or “read data from this file which was generated by Excel,” without knowing the precise details of the CSV format used by Excel.  Programmers can also describe the CSV formats understood by other applications or define their own special-purpose CSV formats.

        csv模块实现类读写CSV格式的表格数据。它允许程序员如此说:“Excel优选这种格式写入数据“,或”从Excel等文件读数据,”不知道Excel所用的CSV格式的精确细节,程序员也可以以其他应用程序理解来描述csv格式,或者定义自己专用的csv格式。

       The csv module’s reader and writer objects read and write sequences.  Programmers can also read and write data in dictionary form using the DictReader and DictWriter classes.

        csv模块的读写器对象可以读取和写入序列。程序员也可以使用DictReader和DictWriter类读取和写入字典形式的数据。

       Note:This version of the csv module doesn’t support Unicode input.  Also, there are currently some issues regarding ASCII NUL characters.  Accordingly, all input should be UTF-8 or printable ASCII to be safe; see the examples in section Examples.

        注意:这个版本(2.7)的csv模块不支持Unicode输入。此外,目前有一些有关于ASCII空字符的问题。因此,所有的输入都应该是UTF-8或者打印安全的ASCII;这些可以在Example部分看实例。

        13.1.1. Module Contents

        The csv module defines the following functions:

  • csv.reader(csvfile, dialect='excel', **fmtparams)

  • Return a reader object which will iterate over lines in the given csvfile.csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.   If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.  An optionaldialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect.  It may be an instance of a subclass of the Dialect class or one of the strings returned by thelist_dialects() function.  The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect.  For full details about the dialect and formatting parameters, see section Dialects and Formatting Parameters.

              返回一个读对象,它会遍历给定的csvfile(可以是支持迭代器协议的任何对象,文件和列表对象都是合适的),每次next()方法调用都会返回一个字符串。如果csvfile是一个文件对象,它必须在有差异的平台上以“b”模式打开文件。一个可选的dialect参数常用来定义一系列特定的csv dialect(不清楚翻译为何为好)参数。它可以是dialect类中的子类或由list_dialects()函数返回的字符串之一的一个实例。其他可选的关键字参数fmtparams可以在当前dialect覆盖个别格式化参数时给出。有关dialect和格式化参数详情,请参照Dialects and Formatting Parameters部分。

       Each row read from the csv file is returned as a list of strings.  No automatic data type conversion is performed.

A short usage example:

>>>

>>> import csv
>>> with open('eggs.csv', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print ', '.join(row)
Spam, Spam, Spam, Spam, Spam, Baked BeansSpam
Lovely Spam, Wonderful Spam

    Changed in version 2.5: The parser is now stricter with respect to multi-line quoted fields. Previously, if a line ended within a quoted field without a terminating newline character, a newline would be inserted into the returned field. This behavior caused problems when reading files which contained carriage return characters within fields. The behavior was changed to return the field without inserting newlines. As a consequence, if newlines embedded within fields are important, the input should be split into lines in a manner which preserves the newline characters.

      在2.5版本发生变化:解释器现在相对于多行引述领域更加严格。之前,如果一行结束但没有终止换行符,换行符将插入到返回字段。这种情况经常在读取包含回车符的文件时发生错误。这种情况已被修改,返回字段不会插入新行。因此,如果新行嵌入字段很重要,输入应分成在其中保留换行字符的方式。

    

  • csv.writer(csvfile, dialect='excel', **fmtparams)

  • Return a writer object responsible for converting the user’s data into delimited strings on the given file-like object.  csvfile can be any object with awrite() method.  If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.  An optional dialectparameter can be given which is used to define a set of parameters specific to a particular CSV dialect.  It may be an instance of a subclass of theDialect class or one of the strings returned by thelist_dialects() function.  The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect.  For full details about the dialect and formatting parameters, see section Dialects and Formatting Parameters. To make it as easy as possible to interface with modules which implement the DB API, the value None is written as the empty string.  While this isn’t a reversible transformation, it makes it easier to dump SQL NULL data values toCSV files without preprocessing the data returned from a cursor.fetch* call. All other non-string data are stringified with str() before being written.

    未完待续。。。


© 著作权归作者所有

共有 人打赏支持
chuang_py
粉丝 3
博文 23
码字总数 6345
作品 0
海淀
程序员
Python CSV文件处理/读写

Python CSV文件处理/读写 CSV全称为“Comma Separated Values”,是一种格式化的文件,由行和列组成,分隔符可以根据需要来变化。 如下面为一csv文件: Title,Release Date,Director And Now ...

liaojie
2014/03/18
0
0
Supporting Python 3(支持python3)——语言区别和暂时解决方法

语言区别和暂时解决方法 这个附录包含一个Python 2和Python 3的不同之处列表以及能不用2to3转换同时在Python 2和Python 3下运行的示例代码。 这个列表是不完整的。在这里列出的只有不包括bug...

在湖闻樟
2015/11/20
0
0
数据挖掘敲门砖--Python爬虫入门

WHAT 数据挖掘是一门综合的技术,随着Ai的兴起,在国内的需求日渐增大。 数据挖掘的职业方向通常有三个,顺便概要地提一下所需的技能(不仅于此) 数据分析方向:需要数理知识支撑,比如概率...

fesoncn
01/02
0
0
Python测试远程端口连接时间

人生苦短 我用Python 问题 最近自己服务器访问别人的服务器,有时候会报超时错误,有时候又能够正常访问别人服务器。 思路 最开始猜测是网络不稳定造成的,但是自己没有收集什么时候超时,什...

亚林瓜子
05/10
0
0
[雪峰磁针石博客]python数据分析快速入门教程2-pandas数据结构

Title: python数据分析快速入门教程2-pandas数据结构 Date: 2018-03-31 9:20 Category: 数据分析 Slug: pythonpandascrash_tutorial2 [雪峰磁针石博客]python数据分析快速入门教程1-开胃菜 ...

Python测试开发人工智能
07/10
0
0

没有更多内容

加载失败,请刷新页面

加载更多

数字转换为字符的L受哪个参数影响

我们知道,如果想把金额带上本位币,一般加上L, 比如: select to_char(salary,'L99,9999.00') from employees; 下面显示如下: SALARY TO_CHAR(SALARY,'L99, 2900 ¥2,900.00 2500 ¥2,500.00 ...

tututu_jiang
20分钟前
1
0
shell编程(告警系统主脚本、告警系统配置文件、告警系统监控项目)

告警系统主脚本 先定义监控系统的各个目录,然后再去定义主脚本,因为是分布式的,所以需要每台机器都这样做,如果事先有创建好各个目录和各个脚本,那么就可以把这些目录和脚本copy到其他机...

蛋黄_Yolks
20分钟前
1
0
SAP HANA Backup and Recovery

SAP HANA Backup and Recovery Skip to end of metadata Created by Paul Power, last modified on Nov 23, 2017 Go to start of metadata Purpose System Privileges How to Perform a Back......

rootliu
22分钟前
1
0
JVM的持久代——何去何从?

本文会介绍一些JVM内存结构的基本概念,然后很快会讲到持久代,来看下Java SE 8发布后它究竟到哪去了。 基础知识 JVM只不过是运行在你系统上的另一个进程而已,这一切的魔法始于一个java命令...

java知识分子
39分钟前
1
0
Hive和HBase的区别

hive是文件的视图,hbase是建了索引的key-value表。 先放结论:Hbase和Hive在大数据架构中处在不同位置,Hbase主要解决实时数据查询问题,Hive主要解决数据处理和计算问题,一般是配合使用。...

飓风2000
45分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部