简体   繁体   中英

Sort integer file names in Python

I have file names as

在此处输入图像描述

When I iterate over them, it iterated in a string manner like:

1
10 
11
.
.
19
2
20
.. so on. I hope you got this. 

I want to iterate them over as integers not strings. Please help me write a function for it.

for i,file in enumerate(sorted(files),key=lambda x: int(os.path.splitext(file)[0]))
     #CODE 

But gives an error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-45-f667164b9d6e> in <module>
     
----> 6 for i,file in enumerate(sorted(files),key=lambda x: int(os.path.splitext(file)[0])):
     

TypeError: 'key' is an invalid keyword argument for enumerate()

Please help me write a function for it. Thanks in advance.

You might try converting all your files to ints first, then sort them.

import os

files = ['0.pdf', '1.pdf', '12.pdf', '15.pdf', '3.pdf', '2.pdf', ]

for i, file_as_number in enumerate(sorted(int(os.path.splitext(file)[0]) for file in files)):
    print(i, file_as_number)
files = ['0.pdf', '1.pdf', '12.pdf', '15.pdf', '3.pdf', '2.pdf' ]
fileDict= {}
SortedFiles = []
for i in range(len(files)):
    fileDict[int(files[i].split('.')[0])] = files[i]
for i in sorted(list(fileDict.keys())):
    SortedFiles.append(fileDict[i])
print (SortedFiles)

['0.pdf', '1.pdf', '2.pdf', '3.pdf', '12.pdf', '15.pdf']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM