'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.
Solution 1:[1]
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']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mohammed Hijaz |

