Python Forum
Cannot 'break' from a "for" loop in a right place
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cannot 'break' from a "for" loop in a right place
#9
I don't think many would agree with your opinion. Break breaks out of the loop in which it appears. Breaking out of all loops would be odd and make break difficult to use. I don't know of a language where break works differently.

Your problem is having two for loops. That is tricky in any language. I would write a function that returns True if a zip file contains a file that matches some pattern. Then your logic is much simpler. Note that none of this has been tested.
def find_file_in_zip(zip_file_name, file_pattern):
    """Return True if file matching file_pattern found in zip file"""
    try:
        with ZipFile(zip_file_name, 'r') as zip_file:
            for filename in zip_file.namelist():
                if pattern in filename:
                    return True
    except OSError:
        pass;
    return False
    
ndir_p = 'Some\\dir\\'
files = [os.path.join(d_to_sacn, i) for i in os.listdir(d_to_sacn)]

for zip_file in sorted(full_list, key=os.path.getmtime):
    zip_file = zip_file.strip()
    if find_file_in_zip(zip_file, 'Debug_TIU')
        parts = zipfile.split('\\')
        shutil.copy(zipfile, ndir_p + parts[-1])    
        break 
tester_V likes this post
Reply


Messages In This Thread
RE: Cannot 'break' from a "for" loop in a right place - by deanhystad - Feb-15-2021, 04:23 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  place 2 windows exactly above each other janeik 3 1,023 Jul-23-2023, 03:12 AM
Last Post: deanhystad
  Code won't break While loop or go back to the input? MrKnd94 2 1,084 Oct-26-2022, 10:10 AM
Last Post: Larz60+
  How to break out of a for loop on button press? philipbergwerf 6 1,915 Oct-06-2022, 03:12 PM
Last Post: philipbergwerf
  break out of for loop? User3000 3 1,552 May-17-2022, 10:18 AM
Last Post: User3000
  Asyncio: Queue consumer gets out of while loop without break. Where exactly and how? saavedra29 2 2,813 Feb-07-2022, 07:24 PM
Last Post: saavedra29
  tkinter control break a while loop samtal 0 2,475 Apr-29-2021, 08:26 AM
Last Post: samtal
  How to break a loop in this case? Blainexi 10 7,501 Sep-24-2020, 04:06 PM
Last Post: Blainexi
  how to break the loop? bntayfur 8 3,173 Jun-07-2020, 11:07 PM
Last Post: bntayfur
  Where should I place GPIO.cleanup() shallanq 2 2,253 Apr-11-2020, 05:02 AM
Last Post: shallanq
  break for loop Agusben 1 1,987 Apr-01-2020, 05:07 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020