[python-win32] problem in looping
Tim Roberts
timr at probo.com
Fri Oct 20 19:07:59 CEST 2006
Ahmed, Shakir wrote:
> HI All,
>
>
>
> Good Afternoon.
>
>
>
> I am trying to use if, elif in python script to work on each county.
> But it works only when the condition is else and jump to the point
> where I need to work but not for case one or two.
>
>
>
> Any help or idea is highly appreciated.
>
>
>
> ...
>
> try:
>
> cycle = open('c:/mydata/county_cycle.txt', 'r')
>
> for countyid in cycle.readlines():
>
> # for countyid = one, two, thr
>
> x = countyid.rstrip()
>
> print x
>
>
>
>
>
> if x=='one':
>
> county_name = open('c:/mydata/county1.txt', 'r')
>
> for county in county_name.readlines():
>
> county = county.rstrip()
>
> print county
>
>
>
> elif x=='two':
>
> county_name = open('c:/mydata/county2.txt', 'r')
>
> for county in county_name.readlines():
>
> county = county.rstrip()
>
> print county
>
>
>
> else:
>
> county_name = open('c:/mydata/county3.txt', 'r')
>
> for county in county_name.readlines():
>
>
>
> county = county.rstrip()
>
> print county
>
>
>
> # the loop come to the next line if the case is else but
> not for case one or two
>
> gp.copy("%smydata1"%county,"%smydata2"%county)
>
Of course, because the indentation makes it part of the "for" loop in
the else clause. If you want that to be executed in all of the loops,
you have to include it in all of the loops.
Any time I see repeated lines of code like this, I look for ways to
combine them. You might consider rewriting it like this:
files = {
'one': 'county1.txt',
'two': 'county2.txt'
}
for countyid in open('c:/mydata/county_cycle.txt):
x = countyid.rstrip()
filename = os.path.join( 'c:/mydata', files.get( x,
'county3.txt' ) )
for county in open( filename ):
county = county.rstrip()
print county
gp.copy( "%smydata1" % county, "%smydata2" % county )
--
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.
More information about the Python-win32
mailing list