开发者

Looping over datasets in Python

I'm trying to write a Python script that will perform the same action on multiple databases. There are too many for me to input them by hand, so I'd like to write a script that will loop over them. Right now, I've gotten as far as the following before getting stuck:

countylist = ['01001','01002','01003','01004']
for item in countylist:

# Local variables...
file_1 = "F:\\file1.shp"
file_2 = "F:\\fileCOUNTYLIST.shp"
output_2 = "F:\\outputCOUNTYLIST.shp"

Basically, I need the items to go where I wrote COUNTYLIST (so the program would call "F:\file01001.shp", "F:\file01002.shp", etc). I couldn't find an answer online. How do I do this?

Thanks a l开发者_运维问答ot!


countylist = ['01001','01002','01003','01004']
file_1 = "F:\\file1.shp"
for item in countylist:
    file_2 = "F:\\file%s.shp" % item
    output_2 = "F:\\output%s.shp" % item
    # Here, I do my commands that are dependent on
    # the name of the file changing.

# Here, outside of the loop, file_2 and output_2 have the last
# value assigned to them.


Simple concatenation will do:

for item in countylist:
   file_2 = 'F:\\file' + item + '.shp'
   output_2 = 'F:\\output' + item + '.shp'


Nobody's used this variation yet, how about the format method for strings...

countylist = ['01001','01002','01003','01004']
for item in countylist:
  file_1 = "F:\\file1.shp"
  file_2 = "F:\\file{0}.shp".format(item)
  output_2 = "F:\\output{0}.shp".format(item)

This style is more flexible because you can not only use the numbered arguments, but also keywords like

 file_2="F:\\file{countylist}.shp".format(countylist=item)

from the manual, "This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code." so it's good to know.

Important Note: I think this method is only available in Python 2.6 and above!


How about:

countylist = ['01001','01002','01003','01004']
for item in countylist:

   # Local variables...
   file_1 = "F:\\file1.shp"
   file_2 = "F:\\file%s.shp" % countylist
   output_2 = "F:\\output%s.shp" % countylist
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜