CSV module in Python

CSV

csv file format is a common spreadsheet and database import and export formats. When I recently RPC call processing server data is often necessary to archive data will be used this convenient format.

Brief introduction

Python csv module encapsulates common functionality using the following simple example:

# Read csv file
import csv
with open ( 'some.csv', 'rb') as f: # b manner using processing may be omitted many problems
    reader = csv.reader(f)
    for row in reader:
        # do something with row, such as row[0],row[1]


import csv
with open ( 'some.csv', 'wb') as f: # b manner using processing may be omitted many problems
    writer = csv.writer(f)
    writer.writerows(someiterable)

By default, read and write using a comma as separator (DELIMITER), reference symbol by quotes (quotechar), when the special circumstances, the characters may need to manually specify, for example:

import csv
with open('passwd', 'rb') as f:
    reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
    for row in reader:
        print row

The above example specifies the colon as the delimiter, and the designated mode is not quote reference. This means that when they are reading content is considered not to be the default reference character ( ") surrounded .quoting the options are:  QUOTE_ALL, QUOTE_MINIMAL, QUOTE_NONNUMERIC, QUOTE_NONE.

Note that a little bit, when writing data writer,  None will be written as an empty string, floating-point type is called  repr() converted into a string method. Therefore, non-string data type is  str() a string stored. Therefore, when referring to the unicode string to be encoded after their storage or manually supplied with csv UnicodeWriter。

Dictionary way to read and write

csv also provides read and write mode similar to a dictionary, as follows:

Format is as follows:

class csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)

class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)

  

 

Which fieldnames specified key value of the dictionary, if not specified then the default reader in the first row elements, be sure to specify this in the writer.

Examples of Use

# Reading
>>> import csv
>>> with open('names.csv') as csvfile:
...     reader = csv.DictReader(csvfile)
...     for row in reader:
...         print(row['first_name'], row['last_name'])
...
Baked Beans
Lovely Spam
Wonderful Spam


# Write

import csv
with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})

other

csv module also relates to other concepts, for example  Dialects, also provides for error handling  exception csv.Error and the like.

Guess you like

Origin www.cnblogs.com/Crush999/p/12004666.html