ssrw can read and write comma separated value and tab delimited files. It also allows indexing by row or column number or by the value in the header row or column.

This was written before the cvs module was available, but I still like the indexing method I use. Since most spread sheets have column titles (or index) in the top row and row titles in the first column, ssrw allows you to use either a string keyword index or a number index, (what column was the amtpayable in or was that the amtdue column?)

code

# ssrw.py
# copyright (c) Jeff Sandys
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
#
"""
NAME:
    ssrw.py    (Spread Sheet Read Write)

DESCRIPTION:
    This is a base object to read and write spreadsheets.  It will read and
    write tab delimited files and comma separated values files.  It can
    get and put items by numeric index or key value index associate to
    the first row or column for dictionary type access.

                      ssrw parameters and methods

    variable default comment -----------------------------------------------

    delim    '\t'    tab delimited file, change default before read
                     change to ',' for comma separated values file

    rcdata           a list of lists to store the rows and column data

    keycol    0      column to use for key word access     change default
    keyrow    0      row to use for key word access        before read

    ckeys            list of column key words,   valid after read
    rkeys            list of row key words,   valid after read

    method(inputs)   comment ----------------------------------------------

    read(filename)   reads the file line by line, parses with the delim value
                     creates the rcdata, ckeys and rkeys lists

    write(filename)  writes the rcdata line by line using the current
                     delim value between each element

    get(column,row)  gets the row column value from the rcdata,
                     column and row can be key words

    put(value,column,row)   puts the value into rcdata at the row column,
                            column and row can be key words


SYNOPSIS:
    ssrw.py [options] filename

OPTIONS:
    -h,--help        this message
    -v,--version     version

EXAMPLES:

>>> cfile = ssrw()                       # make instance of class object
>>> cfile.delim = ','                    # change default delimiter to comma
>>> cfile.read("table.csv")              # read the comma separated value file
>>> cfile.ckeys                          # list the row keys
('curly', 'moe', 'larry')
>>> cfile.get('moe',2)                   # get a cell from column 'moe', row 2
"curly hair"
>>> cfile.put("straight hair",'moe',2)   # put a value into a cell
>>> cfile.delim = '\t'                   # change the delimiter to tab
>>> cfile.write("table.txt")             # save the tab delimited file

"""
#===imports======================
import sys,os,getopt,string,exceptions

#===globals======================
modname="ssrw"
__version__="0.1"

#===utilities====================
def debug(ftn,txt):
    sys.stdout.write(string.join([modname,'.',ftn,':',txt,'\n'],''))
    sys.stdout.flush()

def fatal(ftn,txt):
    msg=string.join([modname,'.',ftn,':FATAL:',txt,'\n'],'')
    raise SystemExit, msg

def usage():
    print __doc__

def trimcr(str):
    if str == '':
        return ''
    if str[-1:] in '\n\r':
        return trimcr(str[:-1])
    else:
        return str

#====================================

#class ssrw(parentclass):
class ssrw:
    #---class variables---
    #--------------------------
    def __init__(self):
        ftn="ssrw"+".__init__"
        #---instance variables---
        self.delim = '\t'
        self.rcdata = []
        self.keycol = 0
        self.keyrow = 0
        self.ckeys = []
        self.rkeys = []
    #===methods==========================
    def read(self,file):
        "reads a file into 'rcdata' parsed by 'delim' string"
        ftn = "read"
        s = open(file, 'r')
        r = trimcr(s.readline())
        while r <> '':
            self.rcdata.append(string.split(r, self.delim))
            r = trimcr(s.readline())
        s.close()
        self.ckeys = self.rcdata[self.keycol]
        self.rkeys = map((lambda x, y=self.keyrow: x[y]), self.rcdata)
        #
    def write(self,file):
        "writes 'rcdata' out as a file with 'delim' between items"
        ftn = "write"
        s = open(file, 'w')
        for item in self.rcdata:
            s.write(string.join(item, self.delim) + "\n")
        s.close()
        #
    def get(self,col,row):
        "gets an item from 'rcdata' by number or key string index"
        ftn = "get"
        # add error handleing
        if type(col) == type("col"):
            col = self.ckeys.index(col)
        if type(row) == type("row"):
            row = self.rkeys.index(row)
        return self.rcdata [row][col]
        #
    def put(self,value,col,row):
        "puts an item into 'rcdata' by number or key string index"
        ftn = "put"
        # add error handleing
        if type(col) == type("col"):
            col = self.ckeys.index(col)
        if type(row) == type("row"):
            row = self.rkeys.index(row)
        self.rcdata[row][col] = value
        #

#=============================
def test():
    ftn = "test"
    z=ssrw()
    z.read("test.txt")

#---main-----------
if __name__ == '__main__':
    ftn = "main"
    opts,pargs=getopt.getopt(sys.argv[1:],'hvab:',
                 ['help','version','aa','bb='])
    for opt in opts:
        if opt[0]=='-h' or opt[0]=='--help':
            print modname+": version="+__version__
            usage()
            sys.exit(0)
        elif opt[0]=='-v' or opt[0]=='--version':
            print modname+": version="+__version__
            sys.exit(0)
    #test()


#===Revision Log===
#Created by mkpythonproj:
#2000-07-26  Jeff Sandys
#

#$Log: ssrw.py$

comments on code

In retrospect the put method probably should use (self,col,row,value).

I used the HarryGeorge mkpythonproj as the starting point for this code.

SpreadSheatReadWrite (last edited 2008-03-04 08:33:03 by localhost)