Loading a Python collection from an text-file

Ilias Lazaridis ilias at lazaridis.com
Sat Jan 28 18:46:10 EST 2006


Ken Starks wrote:
> 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
[...]

the solutions below seems to be the most compact one.

this, or the suggested CSV module within the other messages.

thank's to everyone for the feedback.

[...]
> 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()

.

-- 
http://lazaridis.com



More information about the Python-list mailing list