[Tutor] 'source' in python or preloading variables

Aditya Lal aditya.n.lal at gmail.com
Sat Oct 27 15:42:43 CEST 2007


You can source the file in python provided that you make it python
friendly:-
STN_id[1]='AAA' instead of STN_id[1]=AAA
...

-----------
import re
# Read the file
fd = open('sitelocations')
lines = fd.readlines()
fd.close()

# Make it python friendly: put all values in 'single quotes'
cmd = '\n'.join([re.sub( r'^([^=]+)=(.*)$', r"\1='\2'", v) for v in lines])

# Create variables as list of appropriate size with default values (assuming
0)
max = 5
STN_id, STNlat, STNlon, STNelv = [0]*max, [0]*max, [0]*max, [0]*max

# Execute the command and all your variables are populated ...
exec(cmd)

-------------------
Not sure if this is a better way :) But atleast it will make the file
sitelocations order invariant - implies you can interchange the lines
without breaking the logic.

Caveat - list in python starts at 0 index so STN_id[1] is not the first
element but the second element. But you can filter unwanted items from the
list if you want as in -
[ x for x in STN_id if x != 0 ]

HTH
Aditya

On 10/27/07, 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??
>
> Thanks!
>
>
>
>
> --
> Configuration
> ``````````````````````````
> Plone 2.5.3-final,
> CMF-1.6.4,
> Zope (Zope 2.9.7-final, python 2.4.4, linux2),
> Five 1.4.1,
> Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat
> 4.1.1-51)],
> PIL 1.1.6
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman<http://mail.python.org/mailman/listinfo/tutor>
> /listinfo/tutor <http://mail.python.org/mailman/listinfo/tutor>
>
>


-- 
Aditya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071027/6ee46d87/attachment-0001.htm 


More information about the Tutor mailing list