Solveig
Solveig

Reputation: 55

os.listdir() reading files in a mixed up order

I am trying to read around 120 files in the folder "Data" subfolder "opticalmicroscopy" and it is extremely important that these files be read in consecutive order. However, os.listdir seems to mix up the order which is strange because in "opticalmicroscopy", my files are listen in order. Is there a fix for this?

code

The way my files are listed in "optical microscopy":

enter image description here

Upvotes: 1

Views: 832

Answers (2)

If you do help(os.listdir) you will see the following at the bottom of the help:

    The list is in arbitrary order.  It does not include the special
    entries '.' and '..' even if they are present in the directory.

That means the output isn't in the wrong order, but perhaps not the one you were expecting. If you want to have the output according to alphabetical order you can do

parent_list = os.listdir()
parent_list.sort()
print(parent_list)

You might also like to reverse the list:

parent_list = os.listdir()
parent_list.reverse()
print(parent_list)

Or combine the two to have a reverse sorted list:

parent_list = os.listdir()
parent_list.sort()
parent_list.reverse()
print(parent_list)

Upvotes: 1

Shawn Ramirez
Shawn Ramirez

Reputation: 833

import os
parent_list = sorted(os.listdir("Data\opticalmicroscopy"), key=len)
for child in parent_list:
    print(child)

Upvotes: 2

Related Questions