Python Forum
Is it possible to avoid 2 loops inside another loop?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is it possible to avoid 2 loops inside another loop?
#3
You could simplify things with os.walk()
import os

def _rename_images(self):
    for folder in self._valid_folders():
        self._rename_and_move_images(...)

def _valid_folders(self):
    for folder in self._subfolders(self._root_source):
        dirnames, filenames = next(os.walk(folder))[1:]
        if filenames and not dirnames: # folder not empty and without subfolder
            yield folder

def _subfolders(self, folder):
    for dirname in next(os.walk(folder))[1]:
        yield folder / dirname
Reply


Messages In This Thread
RE: Is it possible to avoid 2 loops inside another loop? - by Gribouillis - Nov-27-2019, 02:30 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Variable definitions inside loop / could be better? gugarciap 2 546 Jan-09-2024, 11:11 PM
Last Post: deanhystad
  How to create a variable only for use inside the scope of a while loop? Radical 10 2,134 Nov-07-2023, 09:49 AM
Last Post: buran
  Help adding a loop inside a loop Extra 31 5,101 Oct-23-2022, 12:16 AM
Last Post: Extra
  Nested for loops - help with iterating a variable outside of the main loop dm222 4 1,729 Aug-17-2022, 10:17 PM
Last Post: deanhystad
  Adding to the dictionary inside the for-loop - weird behaviour InputOutput007 5 2,851 Jan-21-2021, 02:21 PM
Last Post: InputOutput007
  why print('\n') produced 2 new lines instead of 1 - Located inside a FOR loop JulyFire 2 2,627 Jan-10-2021, 01:50 AM
Last Post: JulyFire
  Creating a variables inside FOR loop zazas321 5 4,212 Sep-16-2020, 04:42 PM
Last Post: Naheed
  How to to tie the execution of one process to another inside a loop in Python ignorant_wanderer 0 2,089 Jul-11-2020, 03:44 AM
Last Post: ignorant_wanderer
  Updating a matrix in a time interval inside a for loop vp1989 4 2,982 May-17-2020, 07:15 PM
Last Post: vp1989
  Loop inside loop inside loop L0RTK1PAN1DZ3 4 2,384 Mar-16-2020, 10:44 AM
Last Post: buran

Forum Jump:

User Panel Messages

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