text_to_html.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from datetime import datetime
  2. def save_html_to_file(html_content, file_name):
  3. import os
  4. # 保存 HTML 文件的路径,假设保存到 /home 目录下
  5. current_time = datetime.now().strftime("%Y%m%d%H%M%S")
  6. file_path = f"/home/aihtml/ai_{current_time}.html"
  7. directory = os.path.dirname(file_path)
  8. if not os.path.exists(directory):
  9. os.makedirs(directory)
  10. try:
  11. # 打开文件并写入 HTML 内容
  12. with open(file_path, "w", encoding="utf-8") as file:
  13. file.write(html_content)
  14. print(f"HTML 文件已成功保存到 {file_path}")
  15. except Exception as e:
  16. print(f"保存文件时出现错误: {e}")
  17. return f"ai_{current_time}.html"
  18. if __name__ == "__main__":
  19. # 示例 HTML 内容
  20. text = "Hello, World!"
  21. html_content = f"""
  22. <!DOCTYPE html>
  23. <html lang="en">
  24. <head>
  25. <meta charset="UTF-8">
  26. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  27. <title>保存的文字内容</title>
  28. </head>
  29. <body>
  30. <p>{text}</p>
  31. </body>
  32. </html>
  33. """
  34. # 示例文件名称
  35. file_name = "4213"
  36. # 调用方法保存 HTML 文件
  37. save_html_to_file(html_content, file_name)