John 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!
>  

In your code you don't define your lists before appending to them, I
guess that will cause an error.

>From the 'file()' entry in the Python manuals :
"""
When opening a file, it's preferable to use open() instead of invoking
this constructor directly. file is more suited to type testing (for
example, writing "isinstance(f, file)").
"""

This might work :

# Set initial conditions
STN_id = list()
STNlat = list()
STNlon = list()
STNelv = list()
LDict = dict(STN_id=STN_id, STNlat=STNlat, STNlon=STNlon, STNelv=STNelv)

# Do the job
for L in open('sitelocations','r') :
    LDict[L.split('[')[0]].append(L.split('=')[1].strip('\n'))


HTH

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to