Backend Development 10 min read

Python Book Management System with CRUD Operations and User Authentication

This article presents a Python command‑line book management system that supports adding, searching, deleting, modifying, and displaying books stored in a text file, and extends it with a simple login‑registration feature using file‑based user data, illustrating full CRUD operations and basic authentication.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Book Management System with CRUD Operations and User Authentication

This article introduces a Python command‑line book management system that performs CRUD (Create, Read, Update, Delete) operations on book records stored in a plain‑text file.

The system ensures unique book IDs, allows users to add books, search by name (showing all matches), delete or modify specific entries, and display all books line by line.

Book information is saved in a txt file with each record represented as a dictionary, e.g., {"book_id":"001","book_name":"Python Basics","book_loc":"Shelf A"}.

The core implementation is provided below.

#-*- coding=utf8 -*-
# @author:sololi
# date: 2020/11/12
# 文件说明 : data
import sys

def print_muen():
    print("----菜单提示----")
    print("[1]:添加图书")
    print("[2]:查询图书")
    print("[3]:删除图书")
    print("[4]:修改图书信息")
    print("[5]:显示所有图书")
    print("[6]:退出")


def add_book():
    book_id=input("请输入图书编号")
    book_name=input("请输入图书名称")
    book_loc=input("请输入图书位置")
    for i in books:
        if book_id==i["book_id"]:
            print("编号重复")
            break
    else:
        book={}
        book["book_id"]=book_id
        book["book_name"]=book_name
        book["book_loc"]=book_loc
        books.append(book)
        new_file(books)
        print("添加成功")


def find_book():
    jg=0
    while True:
        book_name=input("输入要找的书名")
        for i in books:
            if book_name==i["book_name"]:
                print(i)
                jg=1
        if jg==0:
            print("查找失败请重新输入")
            continue
        elif jg==1:
            break


def dell_book():
    book_name =input("请输入图书书名")
    i=0
    j=0
    jg=0
    flag=[]
    while i<len(books):
        if books[i]["book_name"]==book_name:
            id=books[i]["book_id"]
            flag.append(id)
            print("图书编号:{}".format(id))
            jg=1
        i+=1
    if jg==0:
        print("找不到图书名")
    if jg==1:
        book_id=input("请输入删除的图书编号")
        i=0
        while j < len(flag):
            if flag[j] == book_id:
                while i < len(books):
                    if books[i]["book_id"] == book_id:
                        del books[i]
                        new_file(books)
                        print("删除成功")
                        break
                    i+=1
                break
            j+=1
        else:
            print("输入的编号有误")
    return books


def modify_book():
    book_name = input("请输入修改的图书名称")
    i = 0
    jg = 0
    flag = []
    while i < len(books):
        if books[i]["book_name"] == book_name:
            id = books[i]["book_id"]
            flag.append(id)
            print("本书图书编号:{}".format(id))
            jg = 1
        i += 1
    if jg == 0:
        print("找不到图书名")
    elif jg == 1:
        book_id = input("请输入修改的图书编号,或者其他需要修改的图书编号")
        for i in books:
            if book_id == i["book_id"]:
                New_id = input("新的图书编号")
                if New_id == i["book_id"]:
                    print("输入编号重复")
                    break
                else:
                    New_name = input("新的图书名称")
                    New_loc = input("新的图书位置")
                    i["book_id"] = New_id
                    i["book_name"] = New_name
                    i["book_loc"] = New_loc
                    new_file(books)
                    break
        else:
            print("输入有误")


def all_book():
    for i  in books:
        print(i)


def read_book(data):
    f = open(data, mode="r", encoding="utf8")
    books = f.readlines()
    f.close()
    for i in range(0, len(books)):
        books[i] = eval(books[i].replace("\n", ""))
    return books


def new_file(books):
    i=0
    nf = open('data', 'w+',encoding='utf8')
    while i<len(books):
        new=str(books[i])
        nf.write(new)
        if i !=len(books)-1:
            nf.write("\n")
        i+=1
    nf.close()

if __name__=="__main__":
    while True:
        data="data"
        books=read_book(data)
        print_muen()
        choice=input("请输入您的选择")
        if choice=='1':
            add_book()
            all_book()
        elif choice=='2':
            find_book()
        elif  choice=='3':
            dell_book()
            all_book()
        elif  choice=='4':
            modify_book()
            all_book()
        elif choice == '5':
            all_book()
        elif choice == '6':
            print("感谢您的使用")
            sys.exit(0)
        else:
            print("您的输入有误,请重新输入")

Additionally, a simple login and registration module is added, storing user credentials in a text file and enforcing password length and complexity rules.

#-*- coding=utf8 -*-
# @author:sololi
# date: 2020/11/3
# 文件说明 :
import sys

def register(username,password):
    #登录功能,且与存储用户表的文本文件进行比较
    shuju=readfile()
    jg1 = 0
    i = 0
    while (i < len(shuju)):
        if (username == shuju[i]["用户名"]):
            print("用户名正确")
            jg1 = 1
            break
        i += 1
    if (jg1 != 1):
        print("用户名错误")
    if (jg1 == 1):
        jg2 = 0
        i = 0
        while (i < len(shuju)):
            if (password == shuju[i]["密码"]):
                print("密码正确")
                jg2 = 1
                break
            i += 1
        if (jg2 != 1):
            print("密码错误")


def logon(username):
    #注册功能,且以正确格式存入文本文件
    shuju=readfile()
    jg3 = 0
    i = 0
    while (i < len(shuju)):
        if (username == shuju[i]["用户名"]):
            print("用户名已经存在")
            jg3 = 1
            break
        i += 1
    if(jg3 == 0):
        while True:
            password = input("请输入注册的密码(密码不能小于6位,且不能为纯数字)")
            if (str.isdigit(password)==1) or (len(password)<6):
                print("密码格式错误")
            else:
                break
        passwordagain=input("请再次确认密码")
        while True:
            if(password==passwordagain):
                break
            else:
                print("两次密码不一致")
                passwordagain = input("请再次确认密码")
        f = open("data", mode='a+', encoding="utf8")
        if shuju == []:
            f.write("用户名:{},密码:{}".format(username, password))
        if shuju != []:
            f.write("\n用户名:{},密码:{}".format(username, password))
        print("注册成功")
        f.close()


def readfile():
    #将数据转换成列表字典形式,放在data.txt中便于后面登录与注册存放数据
    f = open('data', "r+", encoding="utf8")
    shuju = []
    b = []
    aa = {}
    for line in f.readlines():
        line = line.strip('\n')
        a = line.split(' ')
        i = 0
        while i < len(a):
            b = a[i].split(',')
            i += 1
        j = 0
        while j < len(b):
            if b == " ":
                break
            c = b[j].split(':', 1)
            aa[c[0]] = c[1]
            i += 1
            j += 1
        shuju.append(aa.copy())
    f.close()
    return shuju

while True:
    choice=input("登录输入1,注册输入2,其他任意键退出")
    if choice=="1":
        id=input("输入您的账号")
        pw=input("输入您的密码")
        register(id,pw)
        break
    if choice=="2":
        id=input("输入你注册的账号")
        logon(id)
        continue
    else:
        print("退出成功")
        sys.exit(0)
pythonAuthenticationcommand lineCRUDfile-iobook-management
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.