[Tutor] accessing list from a string

A.T.Hofkamp a.t.hofkamp at tue.nl
Tue Nov 25 16:05:28 CET 2008


Bryan Fodness wrote:
> I have a list in a text file that is in the python format.,
> 
>     Positions = [2.5,2.8]

Why do you use Python format for storing data?
(Python format is for storing programs, usually)


> and would like to grab the values.
> 
>     for line in file('list.txt'):
>         if line == Positions:
>             x1,x2=Positions



> I know this does not work.  Is there a direct way to get my x1 and x2
> values.

You can import the Python file, then get the value of Positions.

import myfile
print myfile.Positions



You can read the lines from the file, and use regular expression matching to 
extract the values. That however brings problems like 'what to do when there 
are more such lines', or 'what to do if there are 3 numbers instead of 2'




In general, it is much easier to use a different file format for storing such 
information, eg you could use a .ini file format instead, and use the 
ConfigParser module to load it.


Sincerely,
Albert



More information about the Tutor mailing list