15

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
Jane Sully
  • 3,137
  • 10
  • 48
  • 87
  • 1
    [`os.listdir(path)`](https://docs.python.org/3.4/library/os.html#os.listdir) : Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory. – Chiheb Nexus Jun 13 '17 at 22:35

2 Answers2

29

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)):

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
3

As per documentation: "The list is in arbitrary order"

https://docs.python.org/3.6/library/os.html#os.listdir

If you wish to establish an order (alphabetical in this case), you could sort it.

import os
for file in sorted(os.listdir(path)):
    df = pd.read_csv(path+file)
    // do stuff
jOOsko
  • 608
  • 6
  • 9