概述
用python实现图书管理系统——通过excel文件或者TXT文件存放数据
话不多说,先上图,看看运行起来的效果:
由上图可知,我实现的主要功能:
- 用户注册
- 用户登录
- 添加图书
- 查询图书
- 删除图书
- 修改图书信息
- 观看所有图书信息
接下来详细介绍每个功能如何实现:
(这里,我分别用了两种方法实现对数据的运用)
在整个程序之前我先声明了两个全局变量,用于设立字典列表,分别存放用户信息和书籍信息:
users = []
books = []
举个例子,表明字典列表的详情:
读取数据
读取用户数据
如下为读取TXT文本数据:
每一行利用切割函数切割成相应内容,并放入列表中,再把列表内容传输到全局变量users[]中。
def ReadUsers_Information():
fopen = open("User_Information.txt",encoding="utf-8")
for line in fopen.readlines():
line = str(line).replace("n", "")
users.append({line.split()[0]:line.split()[1],line.split()[2]:line.split()[3],line.split()[4]:line.split()[5],line.split()[6]:line.split()[7]})
fopen.close()
如下为读取excel文本数据:
每一行利用单元格读取方法将单元格内容读取,并存入列表,再将列表内容传输给users[]
def ReadUsers_Information(): wb=openpyxl.load_workbook('User_Information.xlsx')
sh=wb['Sheet']
max_row = sh.max_row
max_column = sh.max_column
head = []
content = []
headcolumn = 1
column = 1
row = 2
while headcolumn <= max_column:
head.append(sh.cell(1,headcolumn).value)
headcolumn = headcolumn + 1
while row <= max_row:
while column <= max_column:
content.append(sh.cell(row,column).value)
column = column + 1
column = 1
row = row + 1
users.append({head[0]:content[0],head[1]:content[1],head[2]:content[2],head[3]:content[3],})
content.clear()
读取书籍数据
与读取用户数据同理,我就不做多咬文嚼字了。
如下为读取TXT文本数据:
def ReadBooks_Information():
fopen = open("Book_Information.txt",encoding="utf-8" )
for line in fopen.readlines():
line = str(line).replace("n", "")
if line != '': #防止line为空的时候执行下列写入语句导致出错
books.append({line.split()[0]: line.split()[1], line.split()[2]: line.split()[3], line.split()[4]: line.split()[5],} )
fopen.close()
如下为读取excel文本数据:
def ReadBooks_Information():
wb = openpyxl.load_workbook( 'Book_Information.xlsx' )
sh = wb['Sheet']
max_row = sh.max_row
max_column = sh.max_column
head = []
content = []
headcolumn = 1
column = 1
row = 2
while headcolumn <= max_column:
head.append( sh.cell( 1, headcolumn ).value )
headcolumn = headcolumn + 1
while row <= max_row:
while column <= max_column:
content.append( sh.cell( row, column ).value )
column = column + 1
column = 1
row = row + 1
books.append( {head[0]: content[0], head[1]: content[1], head[2]: content[2],} )
content.clear()
用户注册
将用户数据存放在TXT文件中:
用open()方法连接TXT文件,
再用write()方法写入数据,
最后还需记得要用close()方法
函数如下:
def AddUsers():
fopen = open("User_Information.txt",'a+',encoding="utf-8")
input_name=str(input("请输入新用户名:"))
input_passwd=str(input("请输入密码:"))
for user in users:
if input_name==user['name']:
print("用户名已存在")
break
else:
fopen.write("nnamet"+input_name+"tpasswdt"+input_passwd+"tstatet1tcountt3")
fopen.close()
将用户信息存放在excel文件中:
我引用的是openpyxl包
打开excel文件方法:
wb= openpyxl.load.workbook("excel文件名")
打开相对应表单方法:
sh=wb['表单名']
函数如下:
def AddUsers():
input_name=str(input("请输入新用户名:"))
input_passwd=str(input("请输入密码:"))
for user in users:
if input_name==user['name']:
print("用户名已存在")
break
else:
wb = openpyxl.load_workbook("User_Information.xlsx")
sh = wb['Sheet']
max_row = sh.max_row
max_column = sh.max_column
number = 1
content = [input_name,input_passwd,1,3]
while number <=max_column:
sh.cell(row=max_row+1,column=number,value=content[number-1])
number = number + 1
wb.save("User_Information.xlsx")
print("新用户创建完成")
用户登陆
需要注意声明的是,在这里增加了一个概念,就是输入三次错误密码,就会把该用户锁定。
函数如下:
def Login ():
input_name=input("请输入用户名:")
input_passwd=input("请输入密码:")
for user in users:
if input_name==user['name']:
if user['state']=='0':
print("账户被锁定")
break
if input_passwd==user['passwd']:
print("登陆成功")
print("您的用户名为:",user['name'])
return 1;
else:
print("密码错误")
user['count'] = str(int(user['count']) - 1)
if user['count']=='0':
user['state']='0'
print("账户被锁定")
else:
print("你还有",user['count'],"次机会")
break
else:
print("用户名错误或未注册")
添加图书
将图书信息添加到TXT文本中:
此处运用的是写方法write()
def AddBook():
fopen = open( "Book_Information.txt", 'a+' ,encoding="utf-8")
input_bookName = str( input( "请输入新图书名:" ) )
input_author = str( input( "请输入作者:" ) )
for book in books:
if input_bookName == book['bookName']:
print( "图书已存在" )
break
else:
bookID = str(int(book['bookID']) + 1)
fopen.write( "nbookNamet" + input_bookName + "tbookIDt" + bookID + "tauthort" + input_author )
fopen.close()
print("图书添加成功")
将图书信息添加到excel文本中
这里运用的是cell()方法,把新增信息一个一个按行、按列输入内容,最后一定记得用save()方法保存操作。
def AddBook():
input_bookName = str( input( "请输入新图书名:" ) )
input_author = str( input( "请输入作者:" ) )
for book in books:
if input_bookName == book['bookName']:
print( "图书已存在" )
break
else:
wb = openpyxl.load_workbook( "Book_Information.xlsx" )
sh = wb['Sheet']
max_row = sh.max_row
max_column = sh.max_column
number = 1
bookID = int( book['bookID'] ) + 1
content = [input_bookName, bookID ,input_author]
while number <= max_column:
sh.cell( row=max_row + 1, column=number, value=content[number - 1] )
number = number + 1
wb.save( "Book_Information.xlsx" )
print( "图书添加成功" )
查询图书
查询图书只需遍历books[]即可。
def SearchBook_ByName():
Search_bookName = input("请输入要找的书籍名:")
for book in books:
if Search_bookName == book['bookName']:
print(book)
break
else:
print("未找到您要找的书籍...")
删除图书
信息存放在TXT文件时:
通过bookName遍历查询books[]中每行内容,如果该行没有查询到相应内容, 则写入TXT文本,但如果改行查询到相应内容,则用continue跳过写入,完整循环后,则删除图书完成。
def DeleteBook_ByName():
bookName_Input = input("请输入要删除的书籍名:")
for book in books:
if bookName_Input == book['bookName']:
readfile = open( "Book_Information.txt", "r" ,encoding="utf-8")
lines = readfile.readlines()
readfile.close()
writefile = open( "Book_Information.txt", "w" ,encoding="utf-8")
for line in lines:
if bookName_Input in line:
continue
writefile.write(line)
print("删除成功")
writefile.close()
break
else:
print("本书籍本就不在图书库中")
信息存放在excel文件中时:
先遍历查询,再利用delete_rows()方法删除整行即可
def DeleteBook_ByName():
bookName_Input = input( "请输入要删除的书籍名:" )
for book in books:
if bookName_Input == book['bookName']:
wb = openpyxl.load_workbook( 'Book_Information.xlsx' )
sh = wb['Sheet']
max_row = sh.max_row
#max_column = sh.max_column
column = 1
row = 2
while row <= max_row:
content = sh.cell( row, column ).value
if content == bookName_Input:
sh.delete_rows(row,1)
wb.save( "Book_Information.xlsx" )
print( "图书删除成功" )
break
row = row + 1
break
else:
print( "本书籍本就不在图书库中" )
修改图书信息
将图书信息存放在TXT文本中:
这里由于图书信息只有书名和作者,所以我这里只提供了如何修改作者名的方法,如若需修改其他数据,类推即可。
遍历查询到图书名后,先打开只读文件,拿出数据到lines中,再打开可写文件,通过遍历lines找到对应位置,再重新输入对应行信息。
def ChangeBookInformation_ByName():
bookName_Input = input("请输入要修改的书籍名:")
for book in books:
if bookName_Input == book['bookName']:
readfile = open( "Book_Information.txt", "r" ,encoding="utf-8")
lines = readfile.readlines()
readfile.close()
writefile = open( "Book_Information.txt", "w" ,encoding="utf-8")
for line in lines:
if bookName_Input in line:
newAuthor_Input = input("请修改作者名为:")
line = 'bookNamet'+bookName_Input+'tbookIDt'+book['bookID']+'tauthort'+newAuthor_Input+'n'
writefile.write(line)
print( "修改成功" )
writefile.close()
break
将图书信息存放在excel文本中:
思路与上面大体相同,所用方法不一罢了。所以不做更详细的解释,以免啰嗦,直接上代码。
def ChangeBookInformation_ByName():
bookName_Input = str(input( "请输入要修改的书籍名:" ))
for book in books:
if bookName_Input == book['bookName']:
wb = openpyxl.load_workbook( 'Book_Information.xlsx' )
sh = wb['Sheet']
max_row = sh.max_row
max_column = sh.max_column
column = 1
row = 2
while row <= max_row:
content = sh.cell( row, column ).value
if content == bookName_Input:
newAuthor_Input = str(input( "请修改作者名为:" ))
sh.cell(row,max_column).value = newAuthor_Input
wb.save( "Book_Information.xlsx" )
print( "图书修改成功" )
break
row = row + 1
break
else:
print("未找到该书籍")
观看所有图书信息
直接遍历打印一遍books[]即可
for book in books:
print(book)
总结
整个图书管理系统体现的是对字典列表和文件读写方面的操作。如何能够更恰当的把数据增删改查,是这个系统的重点。
附件
这里用截图的方式展示TXT文件和excel表格内的格式
鉴于我经常无法及时看到私信,我就直接把代码贴出来吧。
# -*- coding=utf-8 -*-
# @author:YoungKey
# @date:2020/10/24
# @Email:2435575874@qq.com
import openpyxl
users = []
books = []
def ReadUsers_Information():
# fopen = open("User_Information.txt",encoding="utf-8")
# for line in fopen.readlines():
# line = str(line).replace("n", "")
# users.append({line.split()[0]:line.split()[1],line.split()[2]:line.split()[3],line.split()[4]:line.split()[5],line.split()[6]:line.split()[7]})
# fopen.close()
wb=openpyxl.load_workbook('User_Information.xlsx')
sh=wb['Sheet']
max_row = sh.max_row
max_column = sh.max_column
head = []
content = []
headcolumn = 1
column = 1
row = 2
while headcolumn <= max_column:
head.append(sh.cell(1,headcolumn).value)
headcolumn = headcolumn + 1
while row <= max_row:
while column <= max_column:
content.append(sh.cell(row,column).value)
column = column + 1
column = 1
row = row + 1
users.append({head[0]:content[0],head[1]:content[1],head[2]:content[2],head[3]:content[3],})
content.clear()
def ReadBooks_Information():
# fopen = open("Book_Information.txt",encoding="utf-8" )
# for line in fopen.readlines():
# line = str(line).replace("n", "")
# if line != '': #防止line为空的时候执行下列写入语句导致出错
# books.append({line.split()[0]: line.split()[1], line.split()[2]: line.split()[3], line.split()[4]: line.split()[5],} )
# fopen.close()
wb = openpyxl.load_workbook( 'Book_Information.xlsx' )
sh = wb['Sheet']
max_row = sh.max_row
max_column = sh.max_column
head = []
content = []
headcolumn = 1
column = 1
row = 2
while headcolumn <= max_column:
head.append( sh.cell( 1, headcolumn ).value )
headcolumn = headcolumn + 1
while row <= max_row:
while column <= max_column:
content.append( sh.cell( row, column ).value )
column = column + 1
column = 1
row = row + 1
books.append( {head[0]: content[0], head[1]: content[1], head[2]: content[2],} )
content.clear()
def Login ():
input_name=input("请输入用户名:")
input_passwd=input("请输入密码:")
for user in users:
if input_name==user['name']:
if user['state']=='0':
print("账户被锁定")
break
if input_passwd==user['passwd']:
print("登陆成功")
print("您的用户名为:",user['name'])
return 1;
else:
print("密码错误")
user['count'] = str(int(user['count']) - 1)
if user['count']=='0':
user['state']='0'
print("账户被锁定")
else:
print("你还有",user['count'],"次机会")
break
else:
print("用户名错误或未注册")
def MenuOfUserLogin():
print('''
[1]:用户注册
[2]:用户登陆
''')
select=input("请输入您的选项:")
return select
def MenuOfLibrary():
print('''
[1]:添加图书
[2]:查询图书
[3]:删除图书
[4]:修改图书信息
[5]:观看所有图书信息
[6]:退出
''')
select=input("请输入您的选项:")
return select
def AddUsers():
# fopen = open("User_Information.txt",'a+',encoding="utf-8")
# input_name=str(input("请输入新用户名:"))
# input_passwd=str(input("请输入密码:"))
# for user in users:
# if input_name==user['name']:
# print("用户名已存在")
# break
# else:
# fopen.write("nnamet"+input_name+"tpasswdt"+input_passwd+"tstatet1tcountt3")
# fopen.close()
input_name=str(input("请输入新用户名:"))
input_passwd=str(input("请输入密码:"))
for user in users:
if input_name==user['name']:
print("用户名已存在")
break
else:
wb = openpyxl.load_workbook("User_Information.xlsx")
sh = wb['Sheet']
max_row = sh.max_row
max_column = sh.max_column
number = 1
content = [input_name,input_passwd,1,3]
while number <=max_column:
sh.cell(row=max_row+1,column=number,value=content[number-1])
number = number + 1
wb.save("User_Information.xlsx")
print("新用户创建完成")
def AddBook():
# fopen = open( "Book_Information.txt", 'a+' ,encoding="utf-8")
# input_bookName = str( input( "请输入新图书名:" ) )
# input_author = str( input( "请输入作者:" ) )
# for book in books:
# if input_bookName == book['bookName']:
# print( "图书已存在" )
# break
# else:
# bookID = str(int(book['bookID']) + 1)
# fopen.write( "nbookNamet" + input_bookName + "tbookIDt" + bookID + "tauthort" + input_author )
# fopen.close()
# print("图书添加成功")
input_bookName = str( input( "请输入新图书名:" ) )
input_author = str( input( "请输入作者:" ) )
for book in books:
if input_bookName == book['bookName']:
print( "图书已存在" )
break
else:
wb = openpyxl.load_workbook( "Book_Information.xlsx" )
sh = wb['Sheet']
max_row = sh.max_row
max_column = sh.max_column
number = 1
bookID = int( book['bookID'] ) + 1
content = [input_bookName, bookID ,input_author]
while number <= max_column:
sh.cell( row=max_row + 1, column=number, value=content[number - 1] )
number = number + 1
wb.save( "Book_Information.xlsx" )
print( "图书添加成功" )
def SearchBook_ByName():
Search_bookName = input("请输入要找的书籍名:")
for book in books:
if Search_bookName == book['bookName']:
print(book)
break
else:
print("未找到您要找的书籍...")
def DeleteBook_ByName():
# bookName_Input = input("请输入要删除的书籍名:")
# for book in books:
# if bookName_Input == book['bookName']:
# readfile = open( "Book_Information.txt", "r" ,encoding="utf-8")
# lines = readfile.readlines()
# readfile.close()
# writefile = open( "Book_Information.txt", "w" ,encoding="utf-8")
# for line in lines:
# if bookName_Input in line:
# continue
# writefile.write(line)
# print("删除成功")
# writefile.close()
# break
# else:
# print("本书籍本就不在图书库中")
bookName_Input = input( "请输入要删除的书籍名:" )
for book in books:
if bookName_Input == book['bookName']:
wb = openpyxl.load_workbook( 'Book_Information.xlsx' )
sh = wb['Sheet']
max_row = sh.max_row
#max_column = sh.max_column
column = 1
row = 2
while row <= max_row:
content = sh.cell( row, column ).value
if content == bookName_Input:
sh.delete_rows(row,1)
wb.save( "Book_Information.xlsx" )
print( "图书删除成功" )
break
row = row + 1
break
else:
print( "本书籍本就不在图书库中" )
def ChangeBookInformation_ByName():
# bookName_Input = input("请输入要修改的书籍名:")
# for book in books:
# if bookName_Input == book['bookName']:
# readfile = open( "Book_Information.txt", "r" ,encoding="utf-8")
# lines = readfile.readlines()
# readfile.close()
# writefile = open( "Book_Information.txt", "w" ,encoding="utf-8")
# for line in lines:
# if bookName_Input in line:
# newAuthor_Input = input("请修改作者名为:")
# line = 'bookNamet'+bookName_Input+'tbookIDt'+book['bookID']+'tauthort'+newAuthor_Input+'n'
# writefile.write(line)
# print( "修改成功" )
# writefile.close()
# break
bookName_Input = str(input( "请输入要修改的书籍名:" ))
for book in books:
if bookName_Input == book['bookName']:
wb = openpyxl.load_workbook( 'Book_Information.xlsx' )
sh = wb['Sheet']
max_row = sh.max_row
max_column = sh.max_column
column = 1
row = 2
while row <= max_row:
content = sh.cell( row, column ).value
if content == bookName_Input:
newAuthor_Input = str(input( "请修改作者名为:" ))
sh.cell(row,max_column).value = newAuthor_Input
wb.save( "Book_Information.xlsx" )
print( "图书修改成功" )
break
row = row + 1
break
else:
print("未找到该书籍")
if __name__=="__main__":
ReadUsers_Information()
ReadBooks_Information()
while True:
select = MenuOfUserLogin()
if select == '1':
AddUsers()
ReadUsers_Information()
elif select=='2':
while True:
success = Login()
if success == 1:
while True:
select = MenuOfLibrary()
if select == '1':
AddBook()
books.clear()
ReadBooks_Information()
elif select == '2':
SearchBook_ByName()
elif select == '3':
DeleteBook_ByName()
books.clear()
ReadBooks_Information()
elif select == '4':
ChangeBookInformation_ByName()
books.clear()
ReadBooks_Information()
elif select == '5':
for book in books:
print(book)
elif select == '6':
exit(0)
else:
print("输入错误,请重新输入!")
else:
print("输入错误,请重新输入!")
声明:本文转载需注明出处。
最后
以上就是负责哈密瓜为你收集整理的python实现图书管理系统——通过excel文件或者TXT文件存放数据的全部内容,希望文章能够帮你解决python实现图书管理系统——通过excel文件或者TXT文件存放数据所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复