Python: csv module

Examples

import csv

with open('people.csv', mode='w') as f:
    writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(['Name', 'Type', 'Year'])
    writer.writerow(['John Doe', '"IT, Accounting"', '1990'])
    writer.writerow(['Mandy Moe', '"Marketing"', '1980'])

with open('people.csv') as f:
    lines = f.readlines()  # include '\n' in each line
    for line in lines:
        print(line, end="")

with open('people.csv') as f:
    lines = f.read().splitlines()  # remove '\n' in each item in the list
    for line in lines:
        print(line)

with open('people.csv') as f:
    reader = csv.reader(f)  # default to delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL
    count = 0
    for row in reader:
        if count == 0:
            print(f'Header: {",".join(row)}')
        else:
            print(f'{row[0]} has type: {row[1]} at {row[2]}')
        count += 1
    print(f'Done processing {count-1} rows')

Also see: https://docs.python.org/3.8/library/csv.html

>>> import csv
>>> help(csv.reader)

Help on built-in function reader in module _csv:

reader(...)
    csv_reader = reader(iterable [, dialect='excel']
                            [optional keyword args])
        for row in csv_reader:
            process(row)

    The "iterable" argument can be any object that returns a line
    of input for each iteration, such as a file object or a list.  The
    optional "dialect" parameter is discussed below.  The function
    also accepts optional keyword arguments which override settings
    provided by the dialect.

    The returned object is an iterator.  Each iteration returns a row
    of the CSV file (which can span multiple input lines).


>>> help(csv.writer)

Help on built-in function writer in module _csv:

writer(...)
    csv_writer = csv.writer(fileobj [, dialect='excel']
                                [optional keyword args])
        for row in sequence:
            csv_writer.writerow(row)

        [or]

        csv_writer = csv.writer(fileobj [, dialect='excel']
                                [optional keyword args])
        csv_writer.writerows(rows)

    The "fileobj" argument can be any object that supports the file API.
>>> import csv
>>> help(csv)

Help on module csv:

NAME
    csv - CSV parsing and writing.

DESCRIPTION
    This module provides classes that assist in the reading and writing
    of Comma Separated Value (CSV) files, and implements the interface
    described by PEP 305.  Although many CSV files are simple to parse,
    the format is not formally defined by a stable specification and
    is subtle enough that parsing lines of a CSV file with something
    like line.split(",") is bound to fail.  The module supports three
    basic APIs: reading, writing, and registration of dialects.


    DIALECT REGISTRATION:

    Readers and writers support a dialect argument, which is a convenient
    handle on a group of settings.  When the dialect argument is a string,
    it identifies one of the dialects previously registered with the module.
    If it is a class or instance, the attributes of the argument are used as
    the settings for the reader or writer:

        class excel:
            delimiter = ','
            quotechar = '"'
            escapechar = None
            doublequote = True
            skipinitialspace = False
            lineterminator = '\r\n'
            quoting = QUOTE_MINIMAL


    SETTINGS:

        * quotechar - specifies a one-character string to use as the
            quoting character.  It defaults to '"'.
        * delimiter - specifies a one-character string to use as the
            field separator.  It defaults to ','.
        * skipinitialspace - specifies how to interpret whitespace which
            immediately follows a delimiter.  It defaults to False, which
            means that whitespace immediately following a delimiter is part
            of the following field.
        * lineterminator -  specifies the character sequence which should
            terminate rows.
        * quoting - controls when quotes should be generated by the writer.
            It can take on any of the following module constants:

            csv.QUOTE_MINIMAL means only when required, for example, when a
                field contains either the quotechar or the delimiter
            csv.QUOTE_ALL means that quotes are always placed around fields.
            csv.QUOTE_NONNUMERIC means that quotes are always placed around
                fields which do not parse as integers or floating point
                numbers.
            csv.QUOTE_NONE means that quotes are never placed around fields.
        * escapechar - specifies a one-character string used to escape
            the delimiter when quoting is set to QUOTE_NONE.
        * doublequote - controls the handling of quotes inside fields.  When
            True, two consecutive quotes are interpreted as one during read,
            and when writing, each quote character embedded in the data is
            written as two quotes

Leave a Comment

Your email address will not be published.

16 − one =