简体   繁体   中英

Looping through python code

I have a python script which searches a web page for information. currently I add the search term as a parameter when i run my program 'myscript.py searchterm'.

What I would like to do is to have a file with my search terms in, get my script to loop through each one in turn on its own.

so I would populate my list from a file like this....

with open('mylist.txt', 'r') as f:
    searchterms = f.readlines()

I already have my code which looks something like this...just to give you an idea of layout...

counter = 0
try:
    while counter <10:

    #do some other stuff here

    counter=counter+10

except IOError:
    print "No result found!"+""

I need to wrap this in another loop to do this for every item in my list and I'm failing.

I know I need to reset the counter if it gets to 10, move onto my next list item and loop through the above but I don't know how. I find the python docs difficult to understand and I would appreciate a little help.

TIA

If you have a list of search terms, you can easily loop through them and pass them to your existing loop like:

for searchterm in searchterms:   
    counter = 0
    try:
        while counter <10:

        #do some other stuff here with searchterm

        counter=counter+10

    except IOError:
        print "No result found!"+""

Be sure that your counter correctly resets at the beginning of each search term's loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM