Reputation: 3728
Assume that folder A contains the following files:
0.jpg
1.jpg
2.jpg
.
.
.
n.jpg
.
.
.
Now, a python script looks into folder A and using
for path, dirs, files in os.walk(path_to_A):
for filename in files:
fullpath = os.path.join(path, filename)
reads the filename
(reads each image) and updates an array B.
The size of array B is exactly that of the number of images inside A.
My question is, will it ALWAYS be the case that the j-th position of the array will correspond to the j.jpg image file?
For example if the names inside folder A differ ( but are sorted in the lexicographic order - btw, is it really the lexicographic order that is preserved when we list a directory in win or linux OS? ) will this be depicted in array B?
Thanks!
Upvotes: 2
Views: 8238
Reputation: 1372
Original Author: Elliot's on this thread
Use natsort library:
Install the library with the following command for Ubuntu and other Debian versions
Python 2
sudo pip install natsort
Python 3
sudo pip3 install natsort
Details of how to use this library is found here
Upvotes: 0
Reputation: 54213
No, the j-th position will (or at least CAN) vary. From the docs (emphasis mine)
os.listdir(path='.')
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.
That said, if you want it sorted, sorted
produces a stable lexicographically sorted list. sorted(os.listdir("your/path/here"))[n]
should always point to the n-th file (unless your directory changes contents!)
Upvotes: 6