Calico Csv

From IPRE Wiki

Jump to: navigation, search

Csv Module

Overview

The Csv module is useful for reading and writing simple spreadsheet files called comma-separated value files, or CSV files.

API

  • Csv.reader()
  • Csv.writer()

Examples

Using the with statement and reader as an Enumerator of lines:

import Csv
with Csv.reader(pickAFile()) as reader:
    for line in reader:
        print(line)
        # Or, you can also go through each col:
        #for col in line:
        #    print(col)

Using the with statement and readLines():

import Csv
with Csv.reader("myfile.csv") as reader:
    lines = reader.readLines()
print(lines)

Using the with statement, and processing each line:

import Csv
with Csv.reader("myfile.csv") as reader:
    line = reader.readLine()
    while line is not None:
        print(line)
        line = reader.readLine()
print(lines)

Process each line, and calling close() at the end:

import Csv
reader = Csv.reader("myfile.csv")
try:
    line = reader.readLine()
    while line is not None:
        print(line)
        line = reader.readLine()
finally:
    reader.close()

In each of these cases it is import to make sure that reader is closed, else it will be stuck in an open position, and you may not be able to close it without restarting Calico.

Personal tools