generateArticle.py (1886B)
1 import os 2 import re 3 from datetime import datetime 4 5 ARTICLE_DIR = "articles" 6 INDEX_FILE = "index.html" 7 8 title = input("Enter Article title: ") 9 date_str = datetime.now().strftime("%Y-%m-%d") 10 11 if not os.path.exists(ARTICLE_DIR): 12 os.makedirs(ARTICLE_DIR) 13 14 files = os.listdir(ARTICLE_DIR) 15 numbers = [ 16 int(re.search(r"^(\d+)\.html$", f).group(1)) 17 for f in files 18 if re.search(r"^(\d+)\.html$", f) 19 ] 20 next_num = max(numbers) + 1 if numbers else 1 21 new_filename = f"{next_num}.html" 22 new_filepath = os.path.join(ARTICLE_DIR, new_filename) 23 24 html_template = f""" 25 <!doctype html> 26 <html> 27 <head> 28 <meta charset="UTF-8" /> 29 <link rel="stylesheet" href="../style.css" /> 30 <link rel="icon" href="/public/minerva-juppiter.svg" /> 31 <title>{title}</title> 32 </head> 33 <body> 34 <header> 35 <h1>Blog</h1> 36 <h2>by Minerva_Juppiter</h2> 37 <nav> 38 <a href="/">Home</a> 39 / 40 <a href="/about">About</a> 41 </nav> 42 </header> 43 <article> 44 <h1>{title}</h1> 45 <h3>{date_str}</h3> 46 </article> 47 <footer> 48 <p>@all right reserved by Minerva_Juppiter</p> 49 </footer> 50 </body> 51 </html>""" 52 53 with open(new_filepath, "w", encoding="utf-8") as f: 54 f.write(html_template) 55 56 if os.path.exists(INDEX_FILE): 57 with open(INDEX_FILE, "r", encoding="utf-8") as f: 58 lines = f.readlines() 59 60 new_li = f' <li>\n <a href="{ARTICLE_DIR}/{new_filename}">{title}</a>\n </li>\n' 61 62 with open(INDEX_FILE, "w", encoding="utf-8") as f: 63 for line in lines: 64 f.write(line) 65 if "<ul>" in line: 66 f.write(new_li) 67 68 print(f"Generated: {new_filepath}") 69 print(f"Updated: {INDEX_FILE} (Inserted '{title}' at the top of the list)")