import os import pathlib from glob import glob import subprocess files = dict(sorted((int(file.name[4:-12]), file) for file in pathlib.Path('.').rglob('week*-handout.pdf'))) fileList = map(lambda x: f'\"{str(x)}\"', files.values()) command = f"pdftk {' '.join(fileList)} cat output handout.pdf" subprocess.run(command)