Python Forum
Sorting and Merging text-files [SOLVED]
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting and Merging text-files [SOLVED]
#11
An alterative is to use natsort to make it much more flexible.
The problem is called Humans or Natural Sort Order
Example code and make some messy filenames.
from pathlib import Path
from natsort import natsorted, humansorted

outputs = Path(r'G:\div_code\answer')
search = "*file_*.txt"
sorted_outputs = humansorted(outputs.glob(search))
lines = []
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())

with open('lines.txt', 'w') as f:
    f.write('\n'.join(lines))
Output:
G:\div_code\answer\car file_1.txt line1 G:\div_code\answer\file_1_0_.txt line2 G:\div_code\answer\file_33.txt line3 G:\div_code\answer\file____1000.txt line4
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question [SOLVED] Right way to open files with different encodings? Winfried 3 4,947 Jan-18-2025, 02:19 PM
Last Post: Winfried
  [SOLVED] Loop through directories and files one level down? Winfried 3 2,485 Apr-28-2024, 02:31 PM
Last Post: Gribouillis
Question [solved] compressing files with python. SpongeB0B 1 1,302 May-26-2023, 03:33 PM
Last Post: SpongeB0B
  Help replacing word in Mutiple files. (SOLVED) mm309d 0 1,555 Mar-21-2023, 03:43 AM
Last Post: mm309d
  Merging multiple csv files with same X,Y,Z in each Auz_Pete 3 3,408 Feb-21-2023, 04:21 AM
Last Post: Auz_Pete
  azure TTS from text files to mp3s mutantGOD 2 3,326 Jan-17-2023, 03:20 AM
Last Post: mutantGOD
  [SOLVED] [BeautifulSoup] How to get this text? Winfried 6 3,257 Aug-17-2022, 03:58 PM
Last Post: Winfried
  Writing into 2 text files from the same function paul18fr 4 2,764 Jul-28-2022, 04:34 AM
Last Post: ndc85430
  Delete empty text files [SOLVED] AlphaInc 5 3,330 Jul-09-2022, 02:15 PM
Last Post: DeaD_EyE
  Human Sorting (natsort) does not work [SOLVED] AlphaInc 2 2,169 Jul-04-2022, 10:21 AM
Last Post: AlphaInc

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020