0

There's a python list where I stored the filenames from multiple subfolders. Here's a snapshot of the list enter image description here

I tried to sort this list by using such a line

mylist = list_files(MAIN_DIR)
print(sorted(mylist, key=lambda x: int(x.split('/')[-1][:-4].replace('_',''))))

But this doesn't work and thows an error ValueError: invalid literal for int() with base 10 What I need is to sort the list by the filename (the base name) as shown in the snapshot

YasserKhalil
  • 9,138
  • 7
  • 36
  • 95
  • 1
    It looks like you should be doing `x.split('\\')` instead – Ben Grossmann Mar 19 '22 at 20:42
  • 1
    I would work with `os.path.split` to avoid trouble with / and \\ – konstanze Mar 19 '22 at 20:44
  • 1
    You could also use `x.split('.')[0][-1]` to get the character before the file extension – Ben Grossmann Mar 19 '22 at 20:47
  • @Ben Grossmann Thanks a lot. That does the trick `x.split('.')[0][-1]`. Is it possible to get sublists from the main list. I mean each similar filename would go in a sub-list – YasserKhalil Mar 19 '22 at 21:16
  • Another point `-1` means to get only one letter from the filename or I misunderstand that. The real file names are real such as `SampleTest.pdf` – YasserKhalil Mar 19 '22 at 21:19
  • This works fine as for real file names `print(sorted(mylist, key=lambda x: str(x.split('\\')[-1][:-4].replace('_',''))))` – YasserKhalil Mar 19 '22 at 21:21
  • I have the question in a separate thread on this link https://stackoverflow.com/questions/71542240/create-sublist-from-main-python-list-by-condition – YasserKhalil Mar 19 '22 at 21:28
  • @Y I don't understand what you mean by "get sublists from the main list" or "each similar filename". Yes, the `...[-1]` gets you only the final character – Ben Grossmann Mar 19 '22 at 21:29
  • Look there are subfolders in the main folder, and each subfolder has pdf files. In those subfolders, it happened a lot that there are similar pdf names, so I thought of sorting the list as you helped me. Then to create sublists from the main list `[['...\\1.pdf', '...\\1.pdf'], ['...\\2.pdf', '...\\2.pdf', '...\\2.pdf']]`. This is what I meant – YasserKhalil Mar 19 '22 at 21:32

0 Answers0