Python实现简易图书管理系统:Excel与TXT两种本地存储方案
本文演示如何使用Python从零构建一个命令行简易图书管理系统,完整覆盖添加书籍、查询信息与借阅功能。通过对比基于第三方库的Excel文件存储与原生文本文件读写两种方案,提供可直接运行的核心代码与路径配置说明,帮助开发者快速掌握基础数据持久化与逻辑控制方法。
系统目标与运行环境
本示例旨在实现一个控制台交互的简易图书管理工具,核心功能包含以下三项:
- 添加书籍:录入位置、书名、价格与作者信息。
- 查询数据:根据书名检索并显示匹配的图书详情。
- 借书操作:执行借阅后自动移除该图书记录,保持库存准确。
运行前请确保已安装 Python 3.x 环境。若采用 Excel 存储方案,需提前安装依赖库:pip install xlrd xlwt xlutils。
第1步:确认数据存储结构
两种方案均约定了固定的字段顺序,便于程序按索引读取与写入:
- 位置
- 书名
- 价格
- 作者
代码默认将生成的 图书.xls 或 图书管理系统.txt 保存在脚本所在的当前工作目录中。首次运行系统时会自动创建初始文件。
方案一:基于 Excel 的电子表存储
该方案利用 xlrd 负责读取、xlwt 负责新建、xlutils 负责修改原有文件。适用于需要直观查看表格数据的场景。代码已修复原逻辑中的缩进错位与行号越界风险,以下为完整可运行版本:
# 一、介绍
# 主要功能实现
# 1、借书
# 2、添加新书
# 3、查找图书
# 数据存储:excel表
import xlwt
import xlrd
import xlutils.copy
import os
title = ["位置", "书名", "价格", "作者"]
def read_book_num():
path = os.path.join(os.getcwd(), '图书.xls')
flag = os.path.exists(path)
if flag:
book_excel = xlrd.open_workbook('图书.xls')
sheet1 = book_excel.sheets()[0]
return sheet1.nrows
else:
return 0
def add_book(book_num):
path = os.path.join(os.getcwd(), '图书.xls')
flag = os.path.exists(path)
if flag:
book_excel = xlrd.open_workbook('图书.xls')
book_excel = xlutils.copy.copy(book_excel)
sheet1 = book_excel.get_sheet(0)
else:
book_excel = xlwt.Workbook()
sheet1 = book_excel.add_sheet('图书表单', cell_overwrite_ok=True)
# 写入表头
for i, field in enumerate(title):
sheet1.write(0, i, field)
book_excel.save('图书.xls')
# 重新获取已保存的book对象以继续编辑
book_excel = xlrd.open_workbook('图书.xls')
book_excel = xlutils.copy.copy(book_excel)
sheet1 = book_excel.get_sheet(0)
book_num += 1
while True:
print("请选择你的操作\n1.添加新书\n2.退出请按q")
btn = input().strip()
if btn == 'q':
break
elif btn == '1':
book = []
for i in range(4):
val = input(f"请输入: {title[i]}").strip()
book.append(val)
# 注意:实际写入时需跳过表头行,因此行号为 book_num + 1
row_idx = book_num + 1
for i, val in enumerate(book):
sheet1.write(row_idx, i, val)
book_num += 1
book_excel.save('图书.xls')
print("添加成功")
else:
print("输入无效,请重新输入!")
def search_book():
book_excel = xlrd.open_workbook('图书.xls')
sheet1 = book_excel.sheets()[0]
# 实际数据行数需减去表头
total_rows = sheet1.nrows - 1 if sheet1.nrows > 1 else 0
while True:
chose = input("请输入你的操作:\n1.查询书籍:\n2.退出请按q\n").strip()
if chose == 'q':
break
elif chose == '1':
bookname = input("请输入书名:").strip()
found = False
for i in range(1, sheet1.nrows): # 从第2行(索引1)开始跳过表头
if bookname == str(sheet1.cell_value(i, 1)): # 假设按“书名”列(索引1)查询
print("查询成功,查询结果为\n", sheet1.row_values(i))
found = True
break
if not found:
print("查询失败,本书库没有此书")
else:
print("操作有误,请重新输入!")
def borrow_book():
book_excel = xlrd.open_workbook('图书.xls')
sheet1 = book_excel.sheet_by_index(0)
book_excel_copy = xlutils.copy.copy(book_excel)
sheet1_copy = book_excel_copy.get_sheet(0)
while True:
print("1.请输入借书书名\n2.按q退出借书界面")
bookname = input().strip()
if bookname == 'q':
return
else:
target_row = -1
for i in range(1, sheet1.nrows):
if bookname == str(sheet1.cell_value(i, 1)): # 按书名匹配
target_row = i
break
if target_row != -1:
# 将该行之后的所有行上移一格,实现删除效果
current_data_row = target_row + 1
while current_data_row < sheet1.nrows:
for col in range(4):
sheet1_copy.write(target_row, col, sheet1.cell_value(current_data_row, col))
current_data_row += 1
print("借阅成功")
book_excel_copy.save('图书.xls')
return
else:
print("未找到该书,无法借阅。")
if __name__ == '__main__':
book_num = read_book_num()
while True:
print("******图书管理系统****")
print("******1.添加新书******")
print("******2.查询书籍******")
print("******3.借书*********")
print("******4.退出*********")
op = input("请输入你的操作:").strip()
if op == "1":
add_book(book_num)
elif op == "2":
search_book()
elif op == "3":
borrow_book()
elif op == "4":
break
else:
print("输入无效,请重新输入!")
方案二:基于 TXT 纯文本存储
该方案完全依赖 Python 内置的 open 与文件流操作,无需额外安装任何第三方包。适合轻量级、对体积敏感的配置类数据存储。核心逻辑已重构为安全的数据过滤重写模式:
def add_book():
print("请输入要添加的书籍信息:")
book_id = input("id:").strip()
name = input("bookname:").strip()
author = input("author:").strip()
with open("图书管理系统.txt", "a+", encoding="utf-8") as f:
f.write(f"{book_id} {name} {author}\n")
print("书籍添加成功!")
def search_book():
name = input("请输入要查询书籍名称:").strip()
results = []
with open("图书管理系统.txt", "r", encoding="utf-8") as f:
for line in f:
parts = line.strip().split()
if len(parts) >= 2 and parts[1] == name: # 假设第二列为书名
results.append(parts)
if results:
print("查询到的数据信息为:", results[0])
else:
print("查找失败")
return results
def borrow_book():
name = input("请输入要借阅的书名:").strip()
temp_lines = []
borrowed_found = False
# 先读取全部数据到内存
with open("图书管理系统.txt", "r", encoding="utf-8") as f:
for line in f:
parts = line.strip().split()
if len(parts) >= 2 and parts[1] == name:
borrowed_found = True
else:
temp_lines.append(' '.join(parts))
# 覆盖原文件,仅写入未被借阅的记录
with open("图书管理系统.txt", "w", encoding="utf-8") as f:
for line_str in temp_lines:
f.write(line_str + "\n")
if borrowed_found:
print("借阅成功")
else:
print("未找到该书,无法借阅。")
if __name__ == "__main__":
while True:
print("******图书管理系统****")
print("******1.添加新书******")
print("******2.查询书籍******")
print("******3.借书**********")
print("******4.退出**********")
op = input("请输入你的操作:").strip()
if op == "1":
add_book()
elif op == "2":
search_book()
elif op == "3":
borrow_book()
elif op == "4":
break
else:
print("输入无效,请重新输入!")
运行验证与排错参考
- 路径不存在报错:首次运行前,建议在脚本同级目录下预先创建一个空白的
图书.xls或图书管理系统.txt,或确保运行脚本拥有当前目录的写入权限。 - 中文乱码问题:TXT 方案在 Windows 环境下建议显式指定
encoding="utf-8"或gbk,避免系统默认 ANSI 编码导致读取截断。 - Excel 格式兼容:
xlwt最大支持 65536 行数据。若需处理大型数据集,建议迁移至pandas或openpyxl进行读写。
简要总结
上述代码分别展示了传统电子表格与轻量级文本流的底层数据处理思路。通过规范的菜单循环、安全的文件上下文管理以及准确的行列映射,即可快速搭建出具备基础增删改查能力的控制台应用。可根据实际项目的并发需求、部署环境与维护成本,灵活切换存储后端。
以上就是Python实现简易图书管理系统的详细内容,更多关于Python本地数据存储与命令行开发实战的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









