Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reordering filenames in python

I have the following problem:

I need to load several data files. The files are named by my device like:

meas98.dat
meas99.dat
meas100.dat
meas101.dat

With other words, there are no leading zeros. Therefore, if I get the filenames via

os.listdir

they are ordered alphabetically, meaning "meas100.dat" will be the first one. This is obviously not what I want to achieve. The question is what is the most elegant way of doing this?

The (unelegant) way I came up with is:

  • load the filenames
  • extract the filenumber
  • order the filenumber (get the indices)
  • order the filenames with those indices

I am pretty sure python has something build in that can do this while loading the files...

like image 763
Glostas Avatar asked May 31 '26 12:05

Glostas


2 Answers

l = ['meas98.dat',
    'meas99.dat',
    'meas100.dat',
    'meas101.dat']
l.sort(key=lambda i: int(i.strip('meas.dat')))

There is a pythonic way to do this by using pathlib module:

this is the files in my ternimal:

~/so$ ls
meas100.dat  meas98.dat  meas99.dat

this is the files in python:

from pathlib import Path
p = Path('/home/li/so/')
list(p.iterdir())
[PosixPath('/home/li/so/meas99.dat'),
 PosixPath('/home/li/so/meas98.dat'),
 PosixPath('/home/li/so/meas100.dat')]

looks like the pathlib has do this sort for you, you can take a try.

like image 124
宏杰李 Avatar answered Jun 02 '26 00:06

宏杰李


Using slicing [4:-4] to get only numbers from filename - and sorted() will use them to sort filenames.

# random order
l = [
    'meas98.dat',
    'meas100.dat',
    'meas99.dat',
    'meas101.dat',
    'meas1.dat',
]

sorted(l, key=lambda x: int(x[4:-4]))

print(l)

result

['meas1.dat', 'meas98.dat', 'meas99.dat', 'meas100.dat', 'meas101.dat']
like image 20
furas Avatar answered Jun 02 '26 00:06

furas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!