import os import re # Directory containing the .txt files directory = '.' # Name of the output file output_file = 'merged_content.txt' # Function to extract the numerical part of the filename def extract_number(filename): match = re.search(r'content_(\d+)\.txt', filename) return int(match.group(1)) if match else float('inf') # Get a sorted list of files files = sorted([f for f in os.listdir(directory) if f.startswith('content_') and f.endswith('.txt')], key=extract_number) # Open the output file in write mode with open(output_file, 'w', encoding='utf-8') as outfile: # Iterate over the sorted list of files for filename in files: with open(os.path.join(directory, filename), 'r', encoding='utf-8') as infile: # Write the content of the file to the output file outfile.write(infile.read()) outfile.write('\n') # Add a newline after each file's content # Convert the merged text file to .epub format using Calibre's ebook-convert os.system('ebook-convert merged_content.txt merged_content.mobi')