Aug-20-2021, 05:42 PM
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.
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