0

I have found many methods to list every file in multiple directories, like so:

root = "C:\\test\\"
for path, subdirs, files in os.walk(root):
    for name in files:
        print(os.path.join(path, name))

However, I need to list only one file in each directory. I am not looking for any particular order, but I do not need randomness either. Is there a way to get a single file (preferably the "first") in each directory to save the resources it would take to list every file? (This is a Windows filesystem, if that is relevant.)

1
  • the thing is you are already listing all files in the directory in order to find the subdirectories, nothing saved, you could just as well use if files: print(files[0]) Commented Sep 24, 2013 at 16:40

1 Answer 1

1

Try following code:

import os

root = "C:\\test\\"
for path, subdirs, files in os.walk(root):
    if files:
        print(os.path.join(path, min(files)))

UPDATE

To exclude initial directory:

import os
import itertools

root = "C:\\test\\"
for path, subdirs, files in itertools.islice(os.walk(root), 1, None):
    if files:
        print(os.path.join(path, min(files)))

used min to get the first (alphabetically) filename.

Sign up to request clarification or add additional context in comments.

10 Comments

Perfect! While I should have included this in the original question, is there a way to easily exclude the initial directory? (List \test\test.txt, but not \test.txt)
@EpicCyndaquil, Do you want remove C: from C:\test\test.txt?
No @falsetru, perhaps my phrasing was incorrect. I do not want to see C:\test\test.txt at all, but only C:\test\test01\test01.txt, C:\test\test02\test02.txt, etc.
I'm having an issue getting it to work properly from the current directory of the script (which, when printed, returns the proper directory). The structure is identical to that of my inital test folder. Any ideas?
@EpicCyndaquil, Do you mean root = os.path.dirname(os.path.abspath(__file__)) ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.