Объединить тысячи файлов в один на pyhton
Есть 3354 txt файла и нужно их собрать в один. На просторах нашел код:
import glob
read_files = glob.glob("*.txt")
with open("result.txt", "wb") as outfile:
for f in read_files:
with open(f, "rb") as infile:
outfile.write(infile.read())
Но он совмещает файлы 1 с 10, 10 с 100 и т.д. Нужно чтобы он совмещал по порядку 1,2,3,4...3354. Подскажете как это можно сделать?
Если кому нужно:
from natsort import natsorted
import glob
filenames = glob.glob("*.txt")
sort = natsorted(filenames)
with open("result.txt", "wb") as outfile:
for f in sort:
with open(f, "rb") as infile:
outfile.write(infile.read())
Ответы (1 шт):
Автор решения: CrazyElf
→ Ссылка
Используйте модуль natsort для "человеческой" ("натуральной") сортировки. Пример:
from natsort import natsorted
read_files = ['1.txt', '10.txt', '2.txt', '11.txt', '3.txt']
for f in natsorted(read_files):
print(f)
Вывод:
1.txt
2.txt
3.txt
10.txt
11.txt
В вашем случае использование может быть такое:
for f in natsorted(read_files):
^^^^^^^^^