Overview

CSVModels

Abstract

A Django-like declarative framework for working with CSV files.

CSVModels main features are:

  • a convenient way to read/write CSV files
  • easy validation of CSV data

Apart from that, CSVModels, also features a small and easy to extend codebase and a comprehensive test-suite.

Example

Suppose you have the following csv file:

$ cat test.csv
Node;Load case;Moment;Shear
1;LC1;123;23
1;LC2;100;-23
2;LC1;-123;23
2;LC2;-100;-23
3;LC1;123;-23
3;LC2;100;-23

In order to parse this file, all you have to do is to define a class that declares the structure of each csv's rows:

$ cat my_models.py
from csvmodels import RowModel, StringColumn, IntegerColumn, FloatColumn

class MyRow(RowModel):
    node = IntegerColumn()
    load_case = StringColumn()
    moment = FloatColumn()
    shear = FloatColumn()

    _dialect = {
        "has_header_row": True,
        "delimiter": ";"
        }

As you can see the class definition is rather simple. You just add a class attribute for each column of the csv file. While doing so, you also declare the type of each column (string, integer, float etc):

from csvmodels import Reader
from my_models import MyRow

with open("test.csv", "r") as f:
    reader = Reader(MyRow, f)
    for row in reader:
        print(row.node, row.load_case, row.moment)

Documentation

https://csvmodels.readthedocs.org http://packages.python.org/csvmodels

The source code repository of csvmodels can be found at bitbucket.org:

http://bitbucket.org/pmav99/csvmodels

Feedback is greatly appreciated.