Loading a Python collection from an text-file

Ken Starks ken at lampsacos.demon.co.uk
Mon Jan 23 15:31:48 EST 2006


Ilias Lazaridis wrote:

> within a python script, I like to create a collection which I fill with
> values from an external text-file (user editable).
> 
> How is this accomplished the easiest way (if possible without the need
> of libraries which are not part of the standard distribution)?
> 
> something like:
> 
> text-file:
> {peter, 16},
> {anton, 21}
> 
> -
> 
> within code:
> 
> users.load(text-file.txt)
> 
> for user in users
>    user.name
>    user.age
> 
> .
> 
"""
What I do for this kind of work is to use a gnumeric spreadsheet
which saves the data in a simple xml format. xml is much less
error-prone than plain text.
Google for, and study 'The gnumeric file format' by David Gilbert.
You need to know how to unzip the file, and how to write a SAX parser.


If you want to use a plain text format, keep it simple. I would
separate the two fields with tab (thus permit a comma within a field)
and allow 'comment' lines that start with a hash.
You don't need the braces, or the end-of-line comma you included.

# snip 'text-file.txt'
# name and age on one line separated by tab        
Jonny   8
Mary    87
Moses   449


# end-snip 'text-file.txt'
Then:
"""

import string

class user:
    def __init__(self,name,age):
        self.name=name
        self.age=int(age) # or a float, or a time-interval, or date-of-birth

    def show(self):
        print "%s is aged %s" % (self.name, self.age)

if __name__=="__main__":
    users=[]
    filename="text-file.txt"
    fieldsep="\t"
    F=open(filename,"r")
    Lines=F.readlines()
    for L0 in Lines:
        L1=string.strip(L0)
        if not L1.startswith("#"):
            Record=string.split(L1,fieldsep)
            # insert error handling/validation here
            users.append(user(Record[0],Record[1]))

    F.close()
    for user in users:
       user.show()
            




More information about the Python-list mailing list