save_markdown.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import os
  2. from typing import Optional
  3. def save_markdown(content: str, filename: str, directory: Optional[str] = None) -> str:
  4. """
  5. 将字符串内容保存为Markdown文件
  6. :param content: 要保存的Markdown内容
  7. :param filename: 文件名(不需要.md后缀)
  8. :param directory: 保存目录(可选,默认为当前目录)
  9. :return: 保存的文件完整路径
  10. """
  11. try:
  12. # 确保文件名以.md结尾
  13. if not filename.endswith('.md'):
  14. filename += '.md'
  15. # 确定保存路径
  16. if directory:
  17. # 确保目录存在
  18. os.makedirs(directory, exist_ok=True)
  19. filepath = os.path.join(directory, filename)
  20. else:
  21. filepath = filename
  22. # 写入文件
  23. with open(filepath, 'w', encoding='utf-8') as f:
  24. f.write(content)
  25. print(f"[SUCCESS] Markdown文件已保存到: {filepath}")
  26. return filepath
  27. except Exception as e:
  28. print(f"[ERROR] 保存文件时出错: {str(e)}")
  29. raise
  30. # 使用示例
  31. if __name__ == "__main__":
  32. # 示例内容
  33. markdown_content = """# 测试标题
  34. 这是一个测试的Markdown文件。
  35. ## 二级标题
  36. - 列表项1
  37. - 列表项2
  38. ```python
  39. print("Hello, World!")
  40. ```
  41. """
  42. print(markdown_content)
  43. # 保存到当前目录
  44. save_markdown(markdown_content, "test")
  45. # 保存到指定目录
  46. # save_markdown(markdown_content, "test", "D:/output")