Loading a Python collection from an text-file

James Stroud jstroud at ucla.edu
Mon Jan 23 14:40:29 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
> 
> .
> 

This is specific for the text above. You will have to re-craft a regex 
if the actual file is different.

import re

def get_names(afile):
   regex = re.compile(r'{([^,]*),\s*([^}]*)}')
   names = []
   for aline in afile:
     m = regex.search(aline)
     names.append(m.groups())
   return names

def test():
   import cStringIO
   afile = cStringIO.StringIO("{peter, 16},\n{anton, 21}\n")
   print get_names(afile)

test()



More information about the Python-list mailing list