Reputation: 55
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?
The way my files are listed in "optical microscopy":
Upvotes: 1
Views: 832
Reputation: 662
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
Reputation: 833
import os
parent_list = sorted(os.listdir("Data\opticalmicroscopy"), key=len)
for child in parent_list:
print(child)
Upvotes: 2