Home > front end >  printing the files serially using glob
printing the files serially using glob

Time:04-23

I have files in a directory. And the files are named as 1.txt,2.txt,...10.txt...150.txt.

When I use glob function it randomly arranged the files as

1.txt,10.txt....so on

however i want the files to be arranged serially like 1.txt,2.txt...10.txt,11.txt...

i tried the function

import glob
for filename in sorted(glob.glob('*.txt')):
    print(filename)

I hope experts may help me overcoming this problem.

CodePudding user response:

By default, sorted will sort the filenames as strings. That will produce unwanted results:

In [1]: names = [str(n) ".txt" for n in range(1,21)];

In [2]: ' '.join(sorted(names[4:14]))
Out[2]: '10.txt 11.txt 12.txt 13.txt 14.txt 5.txt 6.txt 7.txt 8.txt 9.txt'

You want to sort the filenames numerically. In this case that can be done with a special key function that converts the filename to an integer.

In the case of the example above, like this:

In [3]: ' '.join(sorted(names[4:14], key=lambda s: int(s[:-4])))
Out[3]: '5.txt 6.txt 7.txt 8.txt 9.txt 10.txt 11.txt 12.txt 13.txt 14.txt'

Or in your code:

import glob
for filename in sorted(glob.glob('*.txt'), key=lambda s: int(s[:-4])):
    print(filename)
  • Related