0

I have file names as

enter image description here

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.

3
  • key is an argument to the sorted function. Commented Apr 1, 2021 at 2:50
  • That’s why I want to create a separate function, @AbdulNiyasPM help me please Commented Apr 1, 2021 at 2:56
  • 1
    you have ) in wrong place - it has to be sorted(files, key= ...) but you have sorted(files), key=... Commented Apr 1, 2021 at 5:19

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0
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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.