import os import shutil def clean_filename(name, max_length=200): """Clean the filename to be Windows-friendly and of a limited length.""" # Characters that are not allowed in Windows file names invalid_chars = ['<', '>', ':', '"', '/', '\\', '|', '?', '*'] # Remove invalid characters and replace spaces with underscores cleaned_name = ''.join(c if c not in invalid_chars else '_' for c in name) cleaned_name = cleaned_name.replace(' ', '_') # Limit the length to max_length characters if len(cleaned_name) > max_length: cleaned_name = cleaned_name[:max_length] return cleaned_name # Define the path to the chapters.md file file_path = "chapters.md" with open(file_path, "r") as file: content = file.readlines() # Define the root directory root_directory = "book_structure" # Recursively delete the previous directory and its contents if it exists if os.path.exists(root_directory): shutil.rmtree(root_directory) # Recreate the root directory os.makedirs(root_directory) # Variables to keep track of the current chapter, subsection, and sub-subsection current_chapter = None current_subsection = None current_md_file = None # Iterate over the content lines and create directories and files accordingly for line in content: line = line.strip() # Check for chapter if line.startswith("# "): current_chapter = clean_filename(line[2:]) chapter_dir = os.path.join(root_directory, current_chapter) if not os.path.exists(chapter_dir): os.makedirs(chapter_dir) # Check for subsection elif line.startswith("## "): current_subsection = clean_filename(line[3:]) subsection_dir = os.path.join(chapter_dir, current_subsection) if not os.path.exists(subsection_dir): os.makedirs(subsection_dir) # Check for sub-subsection elif line.startswith("### "): current_md_file = clean_filename(line[4:]) + ".md" md_file_path = os.path.join(subsection_dir, current_md_file) with open(md_file_path, "w") as md_file: pass # Check for entry within sub-subsection elif line.startswith("- "): with open(md_file_path, "a") as md_file: md_file.write(line + "\n") # Zip the updated structure zip_path = "book_structure.zip" shutil.make_archive(zip_path[:-4], 'zip', root_directory) print(f"Folder structure generated and zipped to: {zip_path}")