Os.walk stuck in an infinite loop

I am trying to write a script that traverses a directory and identifies DICOM files with a specified piece of header information. After I have found a file that matches the criteria, I want to add the file directory to the list if it is not already the case.

import dicom
import os
import os.path
import re

param = "PatientID"
val = "7rAgWJ."
rootDir = "C:\\work\\SJM\\WRIX"

dirs = []
i = 0

for subdir, dirs, files in os.walk(rootDir, topdown = True):
    for f in files:
        try:
            f = os.path.join(subdir, f)
            ds = dicom.read_file(f)
            attr = getattr(ds, param)
            if attr == val:
                cur = os.path.dirname(os.path.realpath(f)) 
                if cur not in dirs:
                    dirs.append(cur);

      

My problem is my code never ends because my outer loop is running continuously. The loop loops through files in one of the directories in C: \ work \ SJM \ WRIX \, but never moves to the next folder.

Thank!

+3


source to share


1 answer


You change dirs

which is used os.walk

to figure out which directory will recurse next. Create a separate variable to store the results.



+1


source







All Articles