生成文本格式日历的Python程序

2025年日历生成Python代码

功能介绍

这段代码用于生成2025年的完整日历,并以文本格式保存为一个文件。日历的每个月包含日期和星期的排列,清晰展示了一年的所有日期信息,最后保存为一个 .txt 文件。


实现步骤

  1. 导入 calendar 模块

    • Python 的内置模块 calendar 提供了便捷的方法来生成日历。
    • 使用此模块生成每个月的日期排列。
  2. 定义年份

    • 代码中将年份固定为 2025,也可以修改为其他年份。
  3. 按月生成日历

    • 使用 calendar.month_name 获取月份的英文名称,例如 January
    • 使用 calendar.monthcalendar(year, month) 方法生成某个月的日期列表。该方法返回一个二维数组,其中每个子数组表示一周,日期为整数,空白天为 0
  4. 格式化输出

    • 为了便于阅读,将每一周的日期通过格式化生成一个字符串。
    • 每天的日期都以两位数字对齐,空白天用两个空格表示。
  5. 循环生成全年日历

    • 遍历每个月,将月份名称和对应的日期网格拼接成字符串。
    • 每个月的日历以英文月份名称和 --- 分隔符结束。
  6. 保存为文本文件

    • 将生成的日历保存为 .txt 文件,方便用户下载和查看。
    • 文件路径设置为 2025_calendar.txt
  7. 输出文件路径

    • 最后返回文件路径,用户可以下载并查看生成的日历。

核心代码片段解析

  • 生成月份的网格数据

    cal = calendar.monthcalendar(year, month)
    
    • 生成某个月的日历数据,格式为二维数组,例如:
      [[0, 0, 1, 2, 3, 4, 5], 
       [6, 7, 8, 9, 10, 11, 12],
       [13, 14, 15, 16, 17, 18, 19], 
       [20, 21, 22, 23, 24, 25, 26], 
       [27, 28, 29, 30, 31, 0, 0]]
      
    • 每行表示一周,空白天(如月初或月末)用 0 填充。
  • 格式化每一周

    " ".join(f"{day:2}" if day != 0 else "  " for day in week)
    
    • 将每一周的日期格式化为字符串,并用空格分隔。
    • 如果是空白天(值为 0),用两个空格替代。
  • 保存到文件

    with open(file_path, "w") as file:
        file.write(calendar_text)
    
    • 使用 Python 的文件操作,将生成的日历内容写入到一个文件中。

输出示例

部分文本日历内容示例如下:

### January (1月)
Sun Mon Tue Wed Thu Fri Sat
              1   2   3   4
  5   6   7   8   9  10  11
 12  13  14  15  16  17  18
 19  20  21  22  23  24  25
 26  27  28  29  30  31

---

这种格式清晰易读,可以直接用文本编辑器打开查看。


附Python代码

import calendar

# Generate 2025 calendar in plain text format
year = 2025
calendar_text = ""

for month in range(1, 13):
    calendar_text += f"\n### {calendar.month_name[month]} ({month}月)\n"
    calendar_text += "Sun Mon Tue Wed Thu Fri Sat\n"
    cal = calendar.monthcalendar(year, month)
    for week in cal:
        calendar_text += " ".join(f"{day:2}" if day != 0 else "  " for day in week) + "\n"
    calendar_text += "\n---\n"

# Save the calendar to a text file
file_path = "2025_calendar.txt"
with open(file_path, "w") as file:
    file.write(calendar_text)

file_path


【生成图片格式日历的Python程序】见链接:https://blog.csdn.net/maply/article/details/144869869

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值