MiscUtils.DataTable | index /usr/local/share/webware/MiscUtils/DataTable.py

`DataTable.py
INTRODUCTION
This class is useful for representing a table of data arranged by named
columns, where each row in the table can be thought of as a record:
name phoneNumber
------ -----------
Chuck 893-3498
Bill 893-0439
John 893-5901
This data often comes from delimited text files which typically
have well defined columns or fields with several rows each of which can
be thought of as a record.
Using a DataTable can be as easy as using lists and dictionaries:
table = DataTable('users.csv')
for row in table:
print row['name'], row['phoneNumber']
Or even:
table = DataTable('users.csv')
for row in table:
print '%(name)s %(phoneNumber)s' % row
The above print statement relies on the fact that rows can be treated
like dictionaries, using the column headings as keys.
You can also treat a row like an array:
table = DataTable('something.tabbed', delimiter=' ')
for row in table:
for item in row:
print item,
print
COLUMNS
Column headings can have a type specification like so:
name, age:int, zip:int
Possible types include string, int, float and datetime. However,
datetime is not well supported right now.
String is assumed if no type is specified but you can set that
assumption when you create the table:
table = DataTable(headings, defaultType='float')
Using types like int and float will cause DataTable to actually
convert the string values (perhaps read from a file) to these types
so that you can use them in natural operations. For example:
if row['age']>120:
flagData(row, 'age looks high')
As you can see, each row can be accessed as a dictionary with keys
according the column headings. Names are case sensitive.
ADDING ROWS
Like Python lists, data tables have an append() method. You can append
TableRecords, or you pass a dictionary, list or object, in which case a
TableRecord is created based on given values. See the method docs below
for more details.
FILES
By default, the files that DataTable reads from are expected to be
comma-separated value files.
Limited comments are supported: A comment is any line whose very first
character is a #. This allows you to easily comment out lines in your
data files without having to remove them.
Whitespace around field values is stripped.
You can control all this behavior through the arguments found in the
initializer and the various readFoo() methods:
...delimiter=',', allowComments=True, stripWhite=True
For example:
table = DataTable('foo.tabbed', delimiter=' ',
allowComments=False, stripWhite=False)
You should access these parameters by their name since additional ones
could appear in the future, thereby changing the order.
If you are creating these text files, we recommend the
comma-separated-value format, or CSV. This format is better defined
than the tab delimited format, and can easily be edited and manipulated
by popular spreadsheets and databases.
MICROSOFT EXCEL
On Microsoft Windows systems with Excel and the win32all package
(http://starship.python.net/crew/mhammond/), DataTable will use Excel
(via COM) to read ".xls" files.
from MiscUtils import DataTable
assert DataTable.canReadExcel()
table = DataTable.DataTable('foo.xls')
With consistency to its CSV processing, DataTable will ignore any row
whose first cell is '#' and strip surrounding whitespace around strings.
TABLES FROM SCRATCH
Here's an example that constructs a table from scratch:
table = DataTable(['name', 'age:int'])
table.append(['John', 80])
table.append({'name': 'John', 'age': 80})
print table
QUERIES
A simple query mechanism is supported for equality of fields:
matches = table.recordsEqualTo({'uid': 5})
if matches:
for match in matches:
print match
else:
print 'No matches.'
COMMON USES
* Programs can keep configuration and other data in simple comma-
separated text files and use DataTable to access them. For example, a
web site could read it's sidebar links from such a file, thereby
allowing people who don't know Python (or even HTML) to edit these
links without having to understand other implementation parts of the
site.
* Servers can use DataTable to read and write log files.
FROM THE COMMAND LINE
The only purpose in invoking DataTable from the command line is to see
if it will read a file:
> python DataTable.py foo.csv
The data table is printed to stdout.
CACHING
DataTable uses "pickle caching" so that it can read .csv files faster
on subsequent loads. You can disable this across the board with:
from MiscUtils.DataTable import DataTable
DataTable._usePickleCache = False
Or per instance by passing "usePickleCache=False" to the constructor.
See the docstring of PickleCache.py for more information.
MORE DOCS
Some of the methods in this module have worthwhile doc strings to look
at. See below.
TO DO
* Allow callback parameter or setting for parsing CSV records.
* Perhaps TableRecord should inherit UserList and UserDict and override methods as appropriate...?
* Better support for datetime.
* _types and BlankValues aren't really packaged, advertised or
documented for customization by the user of this module.
* DataTable:
* Parameterize the TextColumn class.
* Parameterize the TableRecord class.
* More list-like methods such as insert()
* writeFileNamed() is flawed: it doesn't write the table column
type
* Should it inherit from UserList?
* Add error checking that a column name is not a number (which could
cause problems).
* Look for various @@ tags through out the code.`

Modules

``

mx.DateTime | os | sys |

Classes

``

DataTable
TableColumn
TableRecord
exceptions.Exception(exceptions.BaseException)
  DataTableError

class DataTable
`` | `Representation of a data table. See the doc string for this module.`

Methods defined here:

__getitem__(self, index)

__init__(self, filenameOrHeadings=None, delimiter=',', allowComments=True, stripWhite=True, defaultType=None, usePickleCache=None)

__len__(self)

__repr__(self)

append(self, object)
  `Append an object to the table.
  If object is not a TableRecord, then one is created,
  passing the object to initialize the TableRecord.
  Therefore, object can be a TableRecord, list, dictionary or object.
  See TableRecord for details.`

canReadExcel(self)

commit(self)

createNameToIndexMap(self)
  `Create speed-up index.
  Invoked by self to create the nameToIndexMap after the table's
  headings have been read/initialized.`

dictKeyedBy(self, key)
  `Return a dictionary containing the contents of the table.
  The content is indexed by the particular key. This is useful
  for tables that have a column which represents a unique key
  (such as a name, serial number, etc.).`

filename(self)

hasHeading(self, name)

heading(self, index)

headings(self)

nameToIndexMap(self)
  `Speed-up index.
  Table rows keep a reference to this map in order to speed up
  index-by-names (as in row['name']).`

numHeadings(self)

readExcel(self, worksheet=1, row=1, column=1)

readFile(self, file, delimiter=',', allowComments=True, stripWhite=True)

readFileNamed(self, filename, delimiter=',', allowComments=True, stripWhite=True, worksheet=1, row=1, column=1)

readLines(self, lines, delimiter=',', allowComments=True, stripWhite=True)

readString(self, string, delimiter=',', allowComments=True, stripWhite=True)

recordsEqualTo(self, dict)

save(self)

setHeadings(self, headings)
  `Set table headings.
  Headings can be a list of strings (like ['name', 'age:int'])
  or a list of TableColumns or None.`

writeFile(self, file)
  `Write the table out as a file.
  @@ 2000-07-20 ce: This doesn't write the column types (like :int) back out.
  @@ 2000-07-21 ce: It's notable that a blank numeric value gets read as zero
  and written out that way. Also, values None are written as blanks.`

writeFileNamed(self, filename)

class DataTableError(exceptions.Exception)

``

Method resolution order:
  DataTableError
  exceptions.Exception
  exceptions.BaseException
  __builtin__.object

Data descriptors defined here:

__weakref__
  `list of weak references to the object (if defined)`

Methods inherited from exceptions.Exception:

__init__(...)
  `x.__init__(...) initializes x; see x.__class__.__doc__ for signature`

Data and other attributes inherited from exceptions.Exception:

__new__ = <built-in method __new__ of type object at 0x8118b60>
  `T.__new__(S, ...) -> a new object with type S, a subtype of T`

Methods inherited from exceptions.BaseException:

__delattr__(...)
  `x.__delattr__('name') <==> del x.name`

__getattribute__(...)
  `x.__getattribute__('name') <==> x.name`

__getitem__(...)
  `x.__getitem__(y) <==> x[y]`

__getslice__(...)
  `x.__getslice__(i, j) <==> x[i:j]
  Use of negative indices is not supported.`

__reduce__(...)

__repr__(...)
  `x.__repr__() <==> repr(x)`

__setattr__(...)
  `x.__setattr__('name', value) <==> x.name = value`

__setstate__(...)

__str__(...)
  `x.__str__() <==> str(x)`

Data descriptors inherited from exceptions.BaseException:

__dict__

args

message
  `exception message`

class TableColumn
`` | `Representation of a table column. A table column represents a column of the table including name and type. It does not contain the actual values of the column. These are stored individually in the rows.`

Methods defined here:

__init__(self, spec)

__repr__(self)

__str__(self)

name(self)

setType(self, type)
  `Set the type (by a string containing the name) of the heading.
  Usually invoked by DataTable to set the default type for columns
  whose types were not specified.`

type(self)

valueForRawValue(self, rawValue)
  `Set correct type for raw value.
  The rawValue is typically a string or value already of the appropriate
  type. TableRecord invokes this method to ensure that values (especially
  strings that come from files) are the correct types (e.g., ints are
  ints and floats are floats).`

class TableRecord
`` | `Representation of a table record.`

Methods defined here:

__getitem__(self, key)

__init__(self, table, values=None)
  `Initialize table record.
  Dispatches control to one of the other init methods based on the type
  of values. Values can be one of three things:
  1. A TableRecord
  2. A list
  3. A dictionary
  4. Any object responding to hasValueForKey() and valueForKey().`

__len__(self)

__repr__(self)

__setitem__(self, key, value)

asDict(self)
  `Return a dictionary whose key-values match the table record.`

asList(self)
  `Return a sequence whose values are the same as the record's.
  The order of the sequence is the one defined by the table.`

get(self, key, default=None)

has_key(self, key)

initFromDict(self, dict)

initFromObject(self, object)
  `Initialize from object.
  The object is expected to response to hasValueForKey(name) and
  valueForKey(name) for each of the headings in the table. It's alright
  if the object returns False for hasValueForKey(). In that case, a
  "blank" value is assumed (such as zero or an empty string). If
  hasValueForKey() returns True, then valueForKey() must return a value.`

initFromSequence(self, values)

items(self)

keys(self)

valueForAttr(self, attr, default=<class MiscUtils.NoDefault at 0x832da1c>)

valueForKey(self, key, default=<class MiscUtils.NoDefault at 0x832da1c>)

values(self)

Functions

``

canReadExcel()

main(args=None)

Data
`` |  | BlankValues = {None: None, "<custom-type 'datetime'>": '', <type 'float'>: 0.0, <type 'int'>: 0, <type 'str'>: ''} DateTimeType = "<custom-type 'datetime'>" ObjectType = "<type 'Object'>" StringTypes = (<type 'str'>, <type 'unicode'>)