-1

How can I sort jpgs in a folder to 1,2,3,4 and so on?

Where do I have a mistake in my code?

import os
path = "/content/drive/My Drive/output_last"
fds = sorted(os.listdir(path))
print(fds)
Jongware
  • 22,200
  • 8
  • 54
  • 100

1 Answers1

0

It sounds like you want to sort numerically:

import os
path = "/content/drive/My Drive/output_last"
fds = sorted(os.listdir(path), key=lambda x: int(x))
print(fds)

If your filenames have the .jpg extension, you will need sort on just the base filename. Something like this:

import os
path = "/content/drive/My Drive/output_last"
fds = sorted(os.listdir(path), key=lambda x: int(x.split('.jpg')[0]))
print(fds)
sloppypasta
  • 1,068
  • 9
  • 15
  • I try, but I have error like this. invalid literal for int() with base 10: '2000.jpg' – Андрей Feb 05 '20 at 18:05
  • I updated the answer to accommodate filenames with `.jpg` extensions. – sloppypasta Feb 05 '20 at 18:12
  • Are you doing `x.split('.jpg')[0]` in order to remove the `.jpg` part to keep only the number? Aren't there more straightforward ways of doing that? – AMC Feb 05 '20 at 18:51
  • @AMC Regex but I don't know if it is faster nor more strait forward. – Error - Syntactical Remorse Feb 05 '20 at 18:54
  • @Error-SyntacticalRemorse If you're making the assumption that all the file names will have the `.jpg` extension, then string slicing would work just fine. – AMC Feb 05 '20 at 18:55
  • I didn't look closely at the answer. That being said split is still the better option (less hard coded), but I would split on `.` not on `.jpg`. Then you can sort by any extension provided it starts with a number. @works_as_coded – Error - Syntactical Remorse Feb 05 '20 at 18:58
  • @Error-SyntacticalRemorse I think once you're dealing with those kinds of nuances it's best to use specialized tools. (relevant: https://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python). – AMC Feb 05 '20 at 19:23
  • @AMC As with all things computational, it really comes down to the use case. Agree that `splitext` is probably the most robust option, but the OP's description does indicate a directory with only `.jpg` files named with only digits. I also agree that string slicing accomplishes exactly the same thing in less characters of code. but you do lose the context. Six months from now I'd prefer to know what I was excising from the filename just by reading the code. – sloppypasta Feb 05 '20 at 21:36