Search code examples
pythonfor-looplistdir

Order in which files are read using os.listdir?


When performing the following code, is there an order in which Python loops through files in the provided directory? Is it alphabetical? How do I go about establishing an order these files are loops through, either by date created/modified or alphabetically).

import os
for file in os.listdir(path)
    df = pd.read_csv(path+file)
    // do stuff

Solution

  • You asked several questions:

    • Is there an order in which Python loops through the files?

    No, Python does not impose any predictable order. The docs say 'The list is in arbitrary order'. If order matters, you must impose it. Practically speaking, the files are returned in the same order used by the underlying operating system, but one mustn't rely on that.

    • Is it alphabetical?

    Probably not. But even if it were you mustn't rely upon that. (See above).

    • How could I establish an order?

    for file in sorted(os.listdir(path)):