Home > OS >  Get list of all file names in a directory with its original in folder order
Get list of all file names in a directory with its original in folder order

Time:05-11

I want to get the list of all file names in a directory but the order of files matters to me. (And I'm using Google Colab if that matters)


P.S: I've accepted the first answer, but just in case know that when I moved my files from google drive to my local PC and run the code, it worked and printed those with the original order. I think there is something with the Google Colab


Suppose my files are in this order in my directory:

file1.txt
file2.txt
file3.txt
...
filen.txt

P.S: These file names are just examples to be clear. In reality my filenames don't have any pattern to be sorted, they are like 1651768933554-b6b4deb3-f245-4763-b38d-71a4b19ca948.wav

When I get the file names via this code:

import glob
for g in glob.glob(MyPath):
  print(g)

I'll get something like this:

file24.txt
file5.txt
file61.txt
...

I want to get the file names in the same order they are in the folder.

I searched as far as I could but I didn't find any SO post solving my problem. Appreciate any help.

P.S: I tried from os import listdir too but didn't work.

CodePudding user response:

The way they exist in the folder isn't really a thing. In reality they are all sitting somewhere in memory and not necessarily next to each other in any way. The GUI usually displays them in alphabetical order, but there are also usually filters you can click to sort them in whatever way you choose.

The reason they are printing that way is because it is alphabetical order. Alphabetically 2 comes before 5 so 24 comes before 5.

CodePudding user response:

Although I agree with the other comment, there is the option to use natural language sorting. This can be accomplished with the natsort package.

>>> from natsort import natsorted
>>> files = ['file24.txt', 'file5.txt', 'file61.txt']
>>> sorted_files = natsorted(files)
>>> sorted_files
['file5.txt', 'file24.txt', 'file61.txt']

Edit: Sorry I didn't see this in the package before. Even better for your needs, see os_sorted from natsort.

>>> from natsort import os_sorted
>>> files = ['file24.txt', 'file5.txt', 'file61.txt']
>>> sorted_files = os_sorted(files)
>>> sorted_files
['file5.txt', 'file24.txt', 'file61.txt']

Or, in the essence of os.listdir()...

>>> sorted_directory = os_sorted(os.listdir(directory_path))
  • Related