I have a while loop based on a MySQLdb cursor in which I need to move to the next iteration based on some conditions in an if statement. Sanitised code looks like this:
row = cur.fetchone()
while row is not None:
unique_id = row[0]
mac = row[1]
url = row[2]
location = old_path + unique_id
os.chdir(location)
file_count = 0
for file in os.listdir(location):
if file.startswith('phone.') and file.endswith('.cfg'):
file_count = file_count + 1
if file_count != 1:
userprompt = 'Multiple phone.MAC.RANDOM.cfg files detected continue?'
cont = query_yes_no(userprompt) # prompt user on what to do next - abort or continue
if cont == False:
debugmsg = 'User requested abort - aborting'
print debugmsg
logger.info(debugmsg)
sys.exit()
elif cont == True:
debugmsg = 'Moving to next on user request'
logger.info(debugmsg)
continue
This code does not behave as expected. When run, if it hits a directory that matches the file_count !=1
condition, the loop appears to run again without advancing to the next row. Unless I have misunderstood the use of continue
I thought it should effectively quit that iteration of the loop and move to the next row.
What am I missing?
代替“继续”,您需要获取下一行:row = cur.fetchone()
You are correct that continue
will move to the next iteration.
However, you are not modifying anything in any iteration. Your statement row is not None
, in your while
never changes. It's either always true or always false.
You probably want to do something like this:
while cur.fetchone() is not None:
#your code
Or better yet:
while cur.fetchone():
#your code
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.