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:
I am pretty sure python has something build in that can do this while loading the files...
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With