1

I am writing my own redundant file cleanup utility (mainly to help me learn Python 2.7)

The processing logic involves three steps:

  1. Walk through potential redundant folder tree getting a filename.

  2. Walk through the "golden" tree searching for a file previously found in 1.

  3. If the files are equal, delete the redundant file (found in 1).

At this point, to save time, I want to break out of searching through golden tree.

Here is what I have so far.

# step 1
for redundant_root, redundant_dirs, redundant_files in os.walk(redundant_input_path):
    redundant_path = redundant_root.split('/')
    for redundant_file in redundant_files:
        redundant_filename = redundant_root + "\\" + redundant_file

# step 2
        for golden_root, golden_dirs, golden_files in os.walk(golden_input_path):
            golden_path = golden_root.split('/')
            for golden_file in golden_files:
                golden_filename = golden_root + "\\" + golden_file

# step 3
                if filecmp.cmp(golden_filename, redundant_filename, True):
                    print("removing " + redundant_filename)
                    os.remove(redundant_filename)

                try:
                    (os.rmdir(redundant_root))
                except:
                    pass

# here is where I want to break from continuing to search through the golden tree.
martineau
  • 119,623
  • 25
  • 170
  • 301
Cool Javelin
  • 776
  • 2
  • 10
  • 26
  • hmmm, closely related to [How to break out of multiple loops in Python?](http://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python) but no answer there clearly covers breaking out of 2nd out of three loops. – Tadhg McDonald-Jensen Aug 10 '16 at 01:40
  • At what point exactly do you want to terminate the search? – martineau Aug 10 '16 at 03:03
  • @TadhgMcDonald-Jensen: Refactoring the inner two loops into afunction would let you use the accepted answer (stop with `return`). If you don't want to create a separate function, another answer suggests creating GetOutOfLoop exception and using a try-catch block around the two inner loops. – hugomg Aug 10 '16 at 04:28

0 Answers0