Harshithah K.s
Harshithah K.s

Reputation: 11

Unsorting files in os.listdir()

In the os.listdir() function when I try to get my files it sorts all my files automatically without me giving any sort function.

Is there any way to get the default output without sorted one?

Upvotes: 1

Views: 86

Answers (1)

mkrieger1
mkrieger1

Reputation: 23139

The documentation says:

The list is in arbitrary order

There is no way to "unsort" this. That it appears to be sorted in your case is coincidence, it might as well not be.

In case of CPython, the listdir function is not even defined in the os module itself, it just forwards the corresponding function from either the nt or the posix module, depending on which OS you are using.

As an example, you can see the source code of the POSIX version here:

https://github.com/python/cpython/blob/5efb1a77e75648012f8b52960c8637fc296a5c6d/Modules/posixmodule.c#L3739

The order in which the entries are added to the result list is determined by calling the readdir function repeatedly, which does not specify any order, either:

The order in which filenames are read by successive calls to readdir() depends on the filesystem implementation; it is unlikely that the names will be sorted in any fashion.


(I can't find the Windows version right now.)

Upvotes: 1

Related Questions