pythonfile

How to select the first file in a directory?


I'm trying to process some files in a directory without knowing their name, and one by one. So I've used os.listdir(path) to list files.

So I have to list files at each call of my function. The problem is when there is a lot of files (like 2000), it takes a loooooong time to list each file and I just want the first one.

Is there any solution to get the first name without listing each files ?


Solution

  • If your goal is to process each file name, use os.walk() generator:

    Help on function walk in module os:
    
    walk(top, topdown=True, onerror=None, followlinks=False)
        Directory tree generator.