# 书籍管理系统 ## 需求 - 依次从用户输入中获取书籍标题、作者、year、出版社 - 将书籍以这样的格式存入db文件中 ``` 书籍标题: Python 编程 作者: Alice, Bob year: 2023 publisher: XYZ出版社 --- 书籍标题: 数据科学入门 作者: Charlie year: 2022 publisher: eagle出版社 --- 书籍标题: 机器学习概论 作者: David, Ella, Frank year: 2021 publisher: 666出版社 --- ``` - 如果用户输入的书籍名称已经存在,那么就弹出提示,并且不再添加 ## 参考代码 ```python # 数据库文件路径 db_file = 'db' # 读取数据库文件,检查书籍标题是否已存在 def check_book_exists(db_file, title): with open(db_file, 'r', encoding="utf-8") as file: for line in file: if line.startswith(f"书籍标题: {title}"): return True return False # 将书籍信息存入db文件 def add_book_to_db(db_file, book_info): with open(db_file, 'a', encoding="utf-8") as file: file.write(book_info + '---\n') # 主程序 while True: # 从用户输入中获取书籍信息 title = input("请输入书籍标题:") if check_book_exists(db_file, title): print("书籍标题已存在,不再添加。") continue # 如果书籍已存在,跳过当前循环,继续下一次循环 author = input("请输入作者:") year = input("请输入出版年份:") publisher = input("请输入出版社:") # 构造书籍信息字符串 book_info = f"书籍标题: {title}\n作者: {author}\nyear: {year}\npublisher: {publisher}\n" # 将书籍信息存入db文件 add_book_to_db(db_file, book_info) print("书籍信息已添加。") ``` >作业5.1提交的内容 > >- 理解程序的运行逻辑 >- 程序运行成功的截图,单独发送给组长