scitools.filetable

Read tabular data from file into NumPy arrays and vice versa.

This module provides functions for 1) reading row-column table data from file into NumPy arrays, and 2) writing two-dimensional NumPy arrays to file in a table fashion.

  • read: Load a table with numbers into a two-dim. NumPy array.
  • write: Write a two-dim. NumPy array a in tabular form.
  • read_columns: As read, but the columns are returned as separate arrays instead of a two-dimensional array.
  • write_columns: As write, but the arguments are comma-separated one-dimensional arrays, one for each column, instead of a two-dimensional array.

The file format requires the same number of “words” (numbers) on each line. Comment lines are allowed, but a blank line indicates a delimiter in the data set, and lines after the blank line will not be read.

Example: Assume we have a data file tmp.dat with the numbers:

0        0.0        0.0        1.0
1        1.0        1.0        2.0
2        4.0        8.0       17.0
3        9.0       27.0       82.0
4       16.0       64.0      257.0
5       25.0      125.0      626.0

The following session demonstrates key functions in this module:

>>> import scitools.filetable as ft
>>> s = open('tmp.dat', 'r')
>>> table = ft.read(s)
>>> s.close()
>>> print table
[[   0.    0.    0.    1.]
 [   1.    1.    1.    2.]
 [   2.    4.    8.   17.]
 [   3.    9.   27.   82.]
 [   4.   16.   64.  257.]
 [   5.   25.  125.  626.]]

>>>
>>> s = open('tmp.dat', 'r')
>>> x, y1, y2, y3 = ft.read_columns(s)
>>> s.close()
>>> print x
[ 0.  1.  2.  3.  4.  5.]
>>> print y1
[  0.   1.   4.   9.  16.  25.]
>>> print y2
[   0.    1.    8.   27.   64.  125.]
>>> print y3
[   1.    2.   17.   82.  257.  626.]
>>>
>>> s = open('tmp2.dat','w')
>>> ft.write(s, table)
>>> s.close()

The tmp2.dat file looks as follows:

0       0       0       1
1       1       1       2
2       4       8       17
3       9       27      82
4       16      64      257
5       25      125     626
scitools.filetable.read(fileobj, commentchar='#')[source]

Load a table with numbers into a two-dim. NumPy array. @param fileobj: open file object. @param commentchar: lines starting with commentchar are skipped (a blank line is an array data delimiter and stops reading). @return: two-dimensional (row-column) NumPy array.

scitools.filetable.read_columns(fileobj, commentchar='#')[source]

As read. Return columns as separate arrays.

scitools.filetable.readfile(filename, commentchar='#')[source]

As read, but a filename (and not a file object) can be given. Return: columns as separate arrays.

scitools.filetable.write(fileobj, a)[source]

Write a two-dim. NumPy array a in tabular form to fileobj.

scitools.filetable.write_columns(fileobj, *columns)[source]

As write, but the column data are represented as one-dimensional arrays.

Previous topic

scitools.errorcheck

Next topic

scitools.globaldata

This Page