2012年6月14日 星期四

[Python Std Library] File Formats : csv — CSV File Reading and Writing


來源自 這裡
Preface :
New in version 2.3.
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.

The csv module implements classes to read and write tabular data in CSV format. 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.

The csv module’s reader and writer objects read and write sequences. Programmers can also read and write data in dictionary form using the DictReaderand DictWriter classes. For more, please refer to PEP 305 - CSV File API
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. These restrictions will be removed in the future.


Module Contents :
The csv module defines the following functions :
csv.reader(csvfile[, dialect='excel'][, fmtparam])
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 optional dialect 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 the list_dialects() function. The other optionalfmtparam 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.

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
>>> spamReader = csv.reader(open('eggs.csv', 'rb'), delimiter=' ', quotechar='|')
>>> for row in spamReader:
... print ', '.join(row)
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, 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.

csv.writer(csvfile[, dialect='excel'][, fmtparam])
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 dialect 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 the list_dialects() function. The other optional fmtparam 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.

A short usage example :

csv.register_dialect(name[, dialect][, fmtparam])
Associate dialect with namename must be a string or Unicode object. The dialect can be specified either by passing a sub-class of Dialect, or byfmtparam keyword arguments, or both, with keyword arguments overriding parameters of the dialect. For full details about the dialect and formatting parameters, see section Dialects and Formatting Parameters.

csv.get_dialect(name)
Changed in version 2.5: This function now returns an immutable Dialect. Previously an instance of the requested dialect was returned. Users could modify the underlying class, changing the behavior of active readers and writers.
Return the dialect associated with name. An Error is raised if name is not a registered dialect name.

csv.list_dialects()
Return the names of all registered dialects.

csv.field_size_limit([new_limit])
New in version 2.5.
Returns the current maximum field size allowed by the parser. If new_limit is given, this becomes the new limit.

The csv module defines the following classes :
class csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)
Create an object which operates like a regular reader but maps the information read into a dict whose keys are given by the optional fieldnames parameter. If the fieldnames parameter is omitted, the values in the first row of the csvfile will be used as the fieldnames. If the row read has more fields than the fieldnames sequence, the remaining data is added as a sequence keyed by the value of restkey. If the row read has fewer fields than the fieldnames sequence, the remaining keys take the value of the optional restval parameter. Any other optional or keyword arguments are passed to the underlying reader instance.

class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)
Create an object which operates like a regular writer but maps dictionaries onto output rows. The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile. The optional restval parameter specifies the value to be written if the dictionary is missing a key in fieldnames. If the dictionary passed to the writerow() method contains a key not found in fieldnames, the optional extrasaction parameter indicates what action to take. If it is set to 'raise' a ValueError is raised. If it is set to 'ignore', extra values in the dictionary are ignored. Any other optional or keyword arguments are passed to the underlying writer instance.

Note that unlike the DictReader class, the fieldnames parameter of the DictWriter is not optional. Since Python’s dict objects are not ordered, there is not enough information available to deduce the order in which the row should be written to the csvfile.

- class csv.Dialect
The Dialect class is a container class relied on primarily for its attributes, which are used to define the parameters for a specific reader or writerinstance.

- class csv.excel
This class defines the usual properties of an Excel-generated CSV file. It is registered with the dialect name 'excel'.

- class csv.excel_tab
This class defines the usual properties of an Excel-generated TAB-delimited file. It is registered with the dialect name 'excel-tab'.

- class csv.Sniffer
The Sniffer class is used to deduce the format of a CSV file. It supports two methods :
sniff(sample, delimiters=None) :
Analyze the given sample and return a Dialect subclass reflecting the parameters found. If the optional delimiters parameter is given, it is interpreted as a string containing possible valid delimiter characters.

has_header(sample) :
Analyze the sample text (presumed to be in CSV format) and return True if the first row appears to be a series of column headers.

An example for Sniffer use :
  1. csvfile = open("example.csv""rb")  
  2. dialect = csv.Sniffer().sniff(csvfile.read(1024))  
  3. csvfile.seek(0)  
  4. reader = csv.reader(csvfile, dialect)  
  5. # ... process CSV file contents here ...  
The csv module defines the following constants :
csv.QUOTE_ALL
Instructs writer objects to quote all fields.

csv.QUOTE_MINIMAL
Instructs writer objects to only quote those fields which contain special characters such as delimiterquotechar or any of the characters inlineterminator.

csv.QUOTE_NONNUMERIC
Instructs writer objects to quote all non-numeric fields.

Instructs the reader to convert all non-quoted fields to type float.

csv.QUOTE_NONE
Instructs writer objects to never quote fields. When the current delimiter occurs in output data it is preceded by the current escapechar character. If escapechar is not set, the writer will raise Error if any characters that require escaping are encountered.

Instructs reader to perform no special processing of quote characters.

The csv module defines the following exception :
- exception csv.Error
Raised by any of the functions when an error is detected.

Reader Objects :
Reader objects (DictReader instances and objects returned by the reader() function) have the following public methods:
csvreader.next()
Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

csvreader.dialect
A read-only description of the dialect in use by the parser.

csvreader.line_num
New in version 2.5.
The number of lines read from the source iterator. This is not the same as the number of records returned, as records can span multiple lines.

DictReader objects have the following public attribute :
csvreader.fieldnames
Changed in version 2.6.
If not passed as a parameter when creating the object, this attribute is initialized upon first access or when the first record is read from the file.

Writer Objects :
Writer objects (DictWriter instances and objects returned by the writer() function) have the following public methods. A row must be a sequence of strings or numbers for Writer objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str() first) for DictWriter objects. Note that complex numbers are written out surrounded by parens. This may cause some problems for other programs which read CSV files (assuming they support complex numbers at all).
csvwriter.writerow(row)
Write the row parameter to the writer’s file object, formatted according to the current dialect.

csvwriter.writerows(rows)
Write all the rows parameters (a list of row objects as described above) to the writer’s file object, formatted according to the current dialect.

Writer objects have the following public attribute :
csvwriter.dialect
A read-only description of the dialect in use by the writer.

DictWriter objects have the following public method :
DictWriter.writeheader()
New in version 2.7.
Write a row with the field names (as specified in the constructor).

Examples :
The simplest example of reading a CSV file :


Reading a file with an alternate format :
  1. import csv  
  2. with open('passwd''rb') as f:  
  3.     reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)  
  4.     for row in reader:  
  5.         print row  
The corresponding simplest possible writing example is :
  1. import csv  
  2. with open('some.csv''wb') as f:  
  3.     writer = csv.writer(f)  
  4.     writer.writerows(someiterable)  
Execution sample of writer :


Registering a new dialect :
  1. import csv  
  2. csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)  
  3. with open('passwd''rb') as f:  
  4.     reader = csv.reader(f, 'unixpwd')  
A slightly more advanced use of the reader — catching and reporting errors :
  1. import csv, sys  
  2. filename = 'some.csv'  
  3. with open(filename, 'rb') as f:  
  4.     reader = csv.reader(f)  
  5.     try:  
  6.         for row in reader:  
  7.             print row  
  8.     except csv.Error, e:  
  9.         sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))  
The csv module doesn’t directly support reading and writing Unicode, but it is 8-bit-clean save for some problems with ASCII NUL characters. So you can write functions or classes that handle the encoding and decoding for you as long as you avoid encodings like UTF-16 that use NULs. UTF-8 is recommended.

Supplement :
Dialects and Formatting Parameters
To make it easier to specify the format of input and output records, specific formatting parameters are grouped together into dialects...

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...