Csv Module. For a lecture motivating the issues involved in csv files, see https://docs.google.com/presentation/d/1wnyLlpuUrdKTlYY_GXyevRaZO9TCcCMgf1Z3DdezSyo/edit?usp=sharing
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']) ## row is one-based because row is string
See Calico Spreadsheet for more information.
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.
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.