Simplicity
Simplicity

Reputation: 48916

Sorting file names by numeric order when mixed with other characters

I have the following code portion by which I intended to print the file names in the correct order:

for root, dirs, files in os.walk(path):
    sortedFiles = sorted(files)
    for file in sortedFiles[0:]:
        print file

This is what I got:

1.i.jpg
10.i.jpg
102.i.jpg
103.i.jpg
104.i.jpg
105.i.jpg
106.i.jpg
107.i.jpg
108.i.jpg
109.i.jpg
11.i.jpg
...
...
...

How can I have 2.i.jpg show up after 1.i.jpg and so forth? That is, having the sequential order in terms of numeric values correct?

Thanks.

Upvotes: 1

Views: 155

Answers (2)

Patriots299
Patriots299

Reputation: 365

Here's an alternative. It is not as straightforward as what Chris suggested though.

files = ['1.i.jpg',
'10.i.jpg',
'102.i.jpg',
'103.i.jpg',
'104.i.jpg',
'105.i.jpg',
'106.i.jpg',
'107.i.jpg',
'108.i.jpg',
'109.i.jpg',
'11.i.jpg',
'2.i.jpg']

numbers = []
for file in files:
    x = file.split('.')[0]
    numbers.append(x)

files.clear()

for i in sorted(numbers, key=int):
    y = i + ".i.jpg"
    files.append(y)

print(files)

Prints:

['1.i.jpg', '2.i.jpg', '10.i.jpg', '11.i.jpg', '102.i.jpg', '103.i.jpg', '104.i.jpg', '105.i.jpg', '106.i.jpg', '107.i.jpg', '108.i.jpg', '109.i.jpg']

Upvotes: 2

Chris
Chris

Reputation: 29742

You can sort with key:

files = ['1.i.jpg',
'10.i.jpg',
'102.i.jpg',
'103.i.jpg',
'104.i.jpg',
'105.i.jpg',
'106.i.jpg',
'107.i.jpg',
'108.i.jpg',
'109.i.jpg',
'11.i.jpg',
'2.i.jpg']

sorted(files, key=lambda x:int(x.split('.')[0]))
['1.i.jpg',
 '2.i.jpg',
 '10.i.jpg',
 '11.i.jpg',
 '102.i.jpg',
 '103.i.jpg',
 '104.i.jpg',
 '105.i.jpg',
 '106.i.jpg',
 '107.i.jpg',
 '108.i.jpg',
 '109.i.jpg']

Upvotes: 3

Related Questions