Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

To specify the problem correctly :i apologize for the confusion Having doubts with breaking early from loop . I have folders - 1995,1996 to 2014 . Each folder has xml files. In some xml files the entry - MaxAmdLetterDate is None. I want to proceed to the next file in the folder, instead right now with break , the program execution goes to the next folder and skips all files in that folder when it encounters a break This is the code

import xml.etree.ElementTree as ET
import os
for yrcnt in range(1995,2015):
    old= old="./old/"+ str(yrcnt)
    for dirpath, subdirs, files in os.walk(old): #folder name in which subfolder>files are present
        print files
        for filename in files:
            if filename.endswith(".xml") == True:
                fl=filename
                print fl
                print "-----Reading current file -------"  + str(fl)
                flnm=str(dirpath)+"/"+str(filename)
                tree1 = ET.parse(flnm)                        #db on system
                root1 = tree1.getroot()
                for ch1 in root1.findall('Award'):
                    aid1 = ch1.find('AwardID').text
                    maxdate1=ch1.find('MaxAmdLetterDate').text
                    print "Max amd date : "+str(maxdate1)
            if maxdate1==None:
                break

Help is appreciated .

ORIGINAL POST: My for loop gets an early exit on encountering a break . Any remedies ?

files=[1,2,3,4,5]
for filename in files:
  print filename
  if filename==3:
     break

o/p:

  1
  2
  3

expected O/p

  1
  2
  4
  5

Thanks !

EDIT: With some comments such as this is expected function of break . Let me elucidate: I want the function to be similar to a range(0,5) , Iam using this as a part of nested loop where I want the loop to go on , and not exit out due to one file .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
244 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is the way break works. If you want to iterate over the whole list, simply remove the break (or if you want to do something with the value, use pass as a placeholder).

values = [1, 2, 3, 4, 5]
for value in values:
    if value == 3:
        pass
    print(value)

Output:

1
2
3
4
5  

If you just want to a skip a value, use continue keyword.

values = [1, 2, 3, 4, 5]
for value in values:
    if value == 3:
        continue
    print(value)

Output:

1
2
4
5 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...