Difference between revisions of "Calico Csv"
Doug Blank (Talk | contribs) (→Overview) |
Doug Blank (Talk | contribs) |
||
Line 1: | Line 1: | ||
− | Csv Module | + | Csv Module. For a lecture motivating the issues involved in csv files, see https://docs.google.com/presentation/d/1wnyLlpuUrdKTlYY_GXyevRaZO9TCcCMgf1Z3DdezSyo/edit?usp=sharing |
= Overview = | = Overview = |
Latest revision as of 00:25, 2 August 2013
Csv Module. For a lecture motivating the issues involved in csv files, see https://docs.google.com/presentation/d/1wnyLlpuUrdKTlYY_GXyevRaZO9TCcCMgf1Z3DdezSyo/edit?usp=sharing
Overview
The Csv module is useful for reading and writing simple spreadsheet files called comma-separated value files, or CSV files.
Note that you can also load a CSV spreadsheet file in Calico, and access it directly. For example:
calico.Open("spreadsheet.csv") document = calico.GetDocument("spreadsheet.csv") row = 0; col = 0 ## row is zero-based because row is int document[col][row] = 23 print(document['A'][1]) ## row is one-based because row is string
See Calico Spreadsheet for more information.
API
- Csv.reader()
- Csv.writer()
Examples
Csv.reader
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.
Csv.writer
from Csv import writer w = writer("filename.csv") w.WriteFields("Column 1", "Column 2", "Column 3", "Column 4") w.WriteFields(1, 2, 3, 4) w.WriteFields(1.1, 2, "", 4) w.Close()
Make sure you close it before trying to look in the file.