I'm trying to loop through files I have, and would like to put every two files in a pair, especially that every two files coming after each other are actually related.
I have the files sorted in my directory, and I used the following to loop through the directory and read the pairs of files:
for root, dirs, files in os.walk(TRAIN_DIR):
for file1, file2 in itertools.izip_longest(files[::2], files[1::2]):
However, I receive file1 and file2 in different orders, and not those two files that should come immediately after each other as in the directory. Does os.walk then return unsorted files? What should I do in order to walk through the files in a sorted order?
This is how my first four files are listed in my system:
0a1a465c-a28d-4926-8a79-81ba83408c52.1.a
0a1a465c-a28d-4926-8a79-81ba83408c52.2.a
0a1b8b67-6c03-47c6-9af9-0e0091148e06.1.a
0a1b8b67-6c03-47c6-9af9-0e0091148e06.2.a
How can I read them in that order?
Thanks.
as here os.walk iterates in what order? written you can add the sort() method before the second loop:
os.walk
does not yield files in any order, as files do not have an order. It's you (or your operating system) that gives them an order by arranging them according to some certain properties: by name, by creation date, by owning user, ...If you want to access your files sorted by some property, then first retrieve them into a list, sort that list, and go on with processing afterwards.