[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:
STN_id.append(line.split('=')[1])
line = sitesFile.next().strip()
STNlat.append(line.split('=')[1])
line = sitesFile.next().strip()
STNlon.append(line.split('=')[1])
line = sitesFile.next().strip()
STNelv.append(line.split('=')[1])
No need for messy regex or unsafe exec.
The dictionary solution is potentially safer
still however since it eliminates the line
order dependancy.
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list