[Tutor] 'source' in python or preloading variables

Alan Gauld alan.gauld at btinternet.com
Sun Oct 28 00:54:09 CEST 2007

"John" <washakie at gmail.com> wrote 

>I have a file sitelocations:
> STN_id[1]=AAA
> STNlat[1]=58.800000
> STNlon[1]=17.400000
> STNelv[1]=20
> STN_id[2]=BBB
> STNlat[2]=42.450000
> STNlon[2]=25.583333
> STNelv[2]=2925
> which in shell scripts I can simple 'source'. 

> In Python I have to:

> sitesFile=file('sitelocations','r')
> sites=sitesFile.readlines()
> i=0;
> for l in sites:
>        if i==0:
>                STN_id.append(l.split('=')[1].strip('\n')); i+=1;
>        elif i==1:
>                STNlat.append(l.split('=')[1].strip('\n')); i+=1;
>        elif i==2:
>                STNlon.append(l.split('=')[1].strip('\n')); i+=1;
>        else:
>                STNelv.append(l.split('=')[1].strip('\n')); i=0;
> Is there a better way??

Yes, use the file as an iterator:

sitesFile = open('sitelocations','r')
for line in sitesFile:
          line = sitesFile.next().strip()
          line = sitesFile.next().strip()
          line = sitesFile.next().strip()

No need for messy regex or unsafe exec.
The dictionary solution is potentially safer 
still however since it eliminates the line 
order dependancy.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list