import os import re # Directory containing the .txt files directory = '.' # Name of the output file output_file = 'merged_content.txt' # Collect and sort filenames numerically file_list = [] for filename in os.listdir(directory): if filename.startswith('content_') and filename.endswith('.txt'): match = re.match(r'content_(\d+)\.txt', filename) if match: number = int(match.group(1)) file_list.append((number, filename)) # Sort by the numeric part file_list.sort() # Write contents in order with open(output_file, 'w', encoding='utf-8') as outfile: for _, filename in file_list: with open(os.path.join(directory, filename), 'r') as infile: outfile.write(infile.read()) outfile.write('\n\n') # Add a page break after each file # Convert the merged text file to PDF using Calibre's ebook-convert os.system("""ebook-convert merged_content.txt output.pdf --pdf-page-numbers""")