Python Forum

Full Version: Human Sorting (natsort) does not work [SOLVED]
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everybody,

With a batch-script I export mutliple text-files to a specific folder where I want to merge them into one.
Therefore I used the type-command in windows cmd which worked fine. But after comparing the files I noticed that the order is wrong. I found out the CMD sorts them differently (file_1,file_10,file_11,file_2,file_3,file_33) instead of how I'm doing it (file_1,file_2,file_3,file_10,file_11,file_33).

This is my script, which does not sort files after human sorting:

#!/usr/bin/env python3

#Imports
import sys
from pathlib import Path
from natsort import natsorted, humansorted

#String Configuration
outputs = Path(r'C:\System\Mediainfo\Outputs\tmp\bts')
search = "*Behind the Scenes #*.txt"
sorted_outputs = humansorted(outputs.glob(search))
lines = []

#Sorting
for path in sorted_outputs:
    if path.is_file():
        print(path)
        with path.open() as fd:
            for line in fd:
                print(line)
                lines.append(line.strip())

#Output Configuration
with open('C:\\System\\Mediainfo\\Outputs\\master\\bts.txt', 'w') as f:
    f.write('\n'.join(lines))

#End
sys.exit()
For sorting pathlib object add key=str.
Test.
from pathlib import Path
from natsort import natsorted, humansorted
from pprint import pprint

outputs = Path(r'G:\div_code\answer\sort_test')
search = "*.txt"
sorted_outputs = humansorted(outputs.glob(search), key=str)
pprint(sorted_outputs)
Output:
[WindowsPath('G:/div_code/answer/sort_test/file_1.txt'), WindowsPath('G:/div_code/answer/sort_test/file_2.txt'), WindowsPath('G:/div_code/answer/sort_test/file_3.txt'), WindowsPath('G:/div_code/answer/sort_test/file_10.txt'), WindowsPath('G:/div_code/answer/sort_test/file_11.txt'), WindowsPath('G:/div_code/answer/sort_test/file_33.txt')]
(Jul-04-2022, 09:56 AM)snippsat Wrote: [ -> ]For sorting pathlib object add key=str.
Test.
from pathlib import Path
from natsort import natsorted, humansorted
from pprint import pprint

outputs = Path(r'G:\div_code\answer\sort_test')
search = "*.txt"
sorted_outputs = humansorted(outputs.glob(search), key=str)
pprint(sorted_outputs)
Output:
[WindowsPath('G:/div_code/answer/sort_test/file_1.txt'), WindowsPath('G:/div_code/answer/sort_test/file_2.txt'), WindowsPath('G:/div_code/answer/sort_test/file_3.txt'), WindowsPath('G:/div_code/answer/sort_test/file_10.txt'), WindowsPath('G:/div_code/answer/sort_test/file_11.txt'), WindowsPath('G:/div_code/answer/sort_test/file_33.txt')]

Ah thank you. That worked fine. Thumbs Up