birthday
This commit is contained in:
65
birthday/birthday.py
Normal file
65
birthday/birthday.py
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
# add_birthday.py
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
|
||||||
|
DATA_FILE = 'birthday/data/birthdays.json'
|
||||||
|
|
||||||
|
|
||||||
|
def load_birthdays():
|
||||||
|
"""从JSON文件中加载生日数据"""
|
||||||
|
if not os.path.exists(DATA_FILE):
|
||||||
|
return []
|
||||||
|
with open(DATA_FILE, 'r', encoding='utf-8') as f:
|
||||||
|
try:
|
||||||
|
return json.load(f)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def save_birthdays(birthdays):
|
||||||
|
"""将生日数据保存到JSON文件"""
|
||||||
|
with open(DATA_FILE, 'w', encoding='utf-8') as f:
|
||||||
|
# indent=4让文件格式更美观, ensure_ascii=False确保中文正常显示
|
||||||
|
json.dump(birthdays, f, indent=4, ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""主函数,用于添加生日"""
|
||||||
|
birthdays = load_birthdays()
|
||||||
|
print("--- 生日信息添加程序 ---")
|
||||||
|
print("当前已记录的生日:")
|
||||||
|
for person in birthdays:
|
||||||
|
print(f"- {person['name']}: {person['birthday']}")
|
||||||
|
print("\n输入新的生日信息(输入姓名时直接按回车结束):")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
name = input("请输入姓名: ").strip()
|
||||||
|
if not name:
|
||||||
|
break
|
||||||
|
|
||||||
|
birthday_str = input(f"请输入 {name} 的生日 (格式 YYYY-MM-DD): ").strip()
|
||||||
|
|
||||||
|
# 简单校验格式 (更复杂的校验可以引入日期库)
|
||||||
|
if len(birthday_str.split('-')) != 3:
|
||||||
|
print("格式错误,请重新输入!")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 检查是否已存在,存在则更新
|
||||||
|
found = False
|
||||||
|
for person in birthdays:
|
||||||
|
if person['name'] == name:
|
||||||
|
print(f"已存在 {name} 的记录,将生日更新为 {birthday_str}")
|
||||||
|
person['birthday'] = birthday_str
|
||||||
|
found = True
|
||||||
|
break
|
||||||
|
|
||||||
|
if not found:
|
||||||
|
birthdays.append({'name': name, 'birthday': birthday_str})
|
||||||
|
print(f"已添加 {name} 的生日: {birthday_str}")
|
||||||
|
|
||||||
|
save_birthdays(birthdays)
|
||||||
|
print("\n生日信息已保存!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user