-2

I am trying to write a function that returns the path of the first file found in a nest of folders. What I have so far is :

def dicom_name(rootDir):
    for dirName, subdirList, fileList in os.walk(rootDir):
        for f in fileList:
            print(dirName,f)
            return(os.path.join(dirName,f))
        break  

Right now if I run this and then run

dcm=dicom_name("test_dir")
print(dcm)

I see "None"

I have tried different placements of the return and break statements. What is the correct way to do what I'm trying to do?

Liz Z
  • 85
  • 1
  • 8
  • 4
    Running this locally for me does not raise a `SyntaxError`, are you sure you've pasted the complete code? – Bono Sep 20 '18 at 16:20
  • Look at the *full error message* - it will tell you the line number of the offending `return` statement, which is certainly not the `return` in the code fragment you posted, since it's clearly not outside of a function. – jasonharper Sep 20 '18 at 16:24
  • You don't need the outer loop at all; `dirName, subdirList, fileList = next(os.walk(rootDir))`. – chepner Sep 20 '18 at 16:35
  • Or the inner loop: `f = next(fileList)`. You would need to check if `fileList` is empty, though, or catch the resulting `StopIteration` exception. – chepner Sep 20 '18 at 16:37
  • I edited the question. Even without the syntax error, the function doesn't return the value I want it to. – Liz Z Sep 20 '18 at 16:42
  • 1
    Your code should be working. Are you sure that the "test_dir" your are giving as an argument is in the same directory with your .py file your are executing? Are you sure that it has files inside? – drkostas Sep 20 '18 at 17:00
  • 1
    The test dir was in the same directory as the .py file I was executing, but I didn't realize I was executing it from a different directory. Feeding in the correct path dcm=dicom_name("../test_dir") worked! – Liz Z Sep 20 '18 at 17:08
  • See my edited answer below. You should remove the `break` to manage the case in which `test_dir` has no file, but only subdirectories. – Amedeo Sep 20 '18 at 17:11

1 Answers1

1

Your don't need the break. Your function is returning always after one execution of the outer thread, even if no file is found in that iteration. Remove the breakand it will work.

As an example, if you have just one file test_dir/a/b.txt, in the first run of the outer thread you have

dirName = test_dir 
subdirList = ['a'] 
fileList = []

and in the second run:

dirName = test_dir/a 
subdirList = [] 
fileList = ['b.txt']

so you want to continue until you find something in the fileList variable.

Amedeo
  • 847
  • 7
  • 17
  • 1
    This was also helpful in solving my problem. The break statement was causing it to to return nothing. It works now. – Liz Z Sep 20 '18 at 17:13