Yotam
Yotam

Reputation: 10485

Iterating files in order of name, Python

I am iterating a bunch of files like so:

for file in glob('./*.dat'):
            print file

And the output is always the following:

./SAN0.dat
./SAN4.dat
./SAN1.dat
./SAN2.dat
./SAN3.dat
./SAN5.dat
./SAN6.dat
./SAN7.dat

How can I iterate them in order of their name, (meaning SAN1.dat would be second, for example)?

Thanks!

Upvotes: 1

Views: 102

Answers (3)

sachin teotia
sachin teotia

Reputation: 141

Following is the easiest way to iterate the files in order of filenames in python-

import os
for file in sorted(os.listdir(path))

Upvotes: 0

gefei
gefei

Reputation: 19766

lst = glob('./*.dat')
lst.sort()

Upvotes: 2

Amber
Amber

Reputation: 526573

for file in sorted(glob('./*.dat')):

Upvotes: 6

Related Questions