Loading a Python collection from an text-file

Bengt Richter bokr at oz.net
Fri Jan 27 07:48:36 EST 2006


On Mon, 23 Jan 2006 21:00:55 +0200, Ilias Lazaridis <ilias at lazaridis.com> 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
>
>.
>
>-- 
>http://lazaridis.com

I'd use a CSV text file, maybe something like (only tested as far as you see!):

----< for_ilias_lazaridis.py >----------------------------------------------
import csv, types

class Fields(object):
    def __init__(self, kvpairs): self.__dict__.update(kvpairs)
        
class Users(object):
    def __init__(self):
        self.userlist=[]
    def load(self, lineiter):
        if isinstance(lineiter, basestring):
            lineiter = open(lineiter) # assume it's a file path
        csvit = csv.reader(lineiter)
        self.colnames = colnames = csvit.next()
        typenames = csvit.next()
        self.coltypes =coltypes = [getattr(types, name.capitalize()+'Type')
                                        for name in typenames]
        for row in csvit:
            self.userlist.append(Fields(zip(colnames, (t(s) for t,s in zip(coltypes, row)))))
    def __iter__(self): return iter(self.userlist)
        
def test():
    import StringIO
    f = StringIO.StringIO("""\
name,age
String,Int
peter,16
anton,21
""")
    users = Users()
    users.load(f)
    for user in users:
        print user.name, user.age
    for user in users:
        for name in users.colnames:
            print '%s=%s,'%(name, getattr(user, name)),
        print

if __name__ == '__main__': test()
-----------------------------------------------------------------------

Output:

[ 4:47] C:\pywk\clp>py24 for_ilias_lazaridis.py
peter 16
anton 21
name=peter, age=16,
name=anton, age=21,

(the first for user in users loop presumes knowledge of the field names name and age.
The second gets them automatically from the names loaded in the load method from
the first line of the text file. The second line expects type names as you see
in the types module, except without the "Type" suffix.

Perhaps you can adapt for your purposes.

Regards,
Bengt Richter



More information about the Python-list mailing list