python实现图书管理系统

Python基于函数模块化设计的图书管理系统

函数模块操作权限内存调用
Python函数的模块化设计可以解决现实中的问题。该过程就是抽象的问题进行函数模块化设计。图书管理系统是现实生活最为简单的实例,下面我们将演示以下如何通过模块化的程序设计来实现。
首先,我们先来学习一下python函数模块:
定义一个函数:
1.函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 ()。
2.任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数。
3.函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
4.函数内容以冒号 : 起始,并且缩进。
5. return [表达式] 结束函数,选择性地返回一个值给调用方,不带表达式的 return 相当于返回 None。

python实现图书管理系统
图书管理系统需要实现图书的增加,删除,修改,查阅,借阅,归还,个人信息修改。
用户注册函数:
def logon():
    print("欢迎来到图书管理系统注册页面~")
    username = input("请输入用户名:")
    if len(username) < 6:
        print("用户名不能小于6个字符")
    else:
        email = input("请输入邮箱:")
        password = input("请输入密码:")
        if len(password) < 8:
            print("密码不能少于8位")
        else:
            rpassword = input("请确认密码:")
            if password == rpassword:
                print("注册成功!")

                preserve_data(path, [username, '   ' + email, '   ' + password + '\n'])
                login_tips = input('是否登录?(yes/no)')
                if login_tips == 'yes':
                    login()
                else:
                    pass
                return True
            else:
                print("两次输入的密码不一致,请重新输入!")

                logon()

path = r'C:\Users\ASUS\Desktop\2021课程\python\User.txt'

def preserve_data(file_path, data):

    with open(file_path, 'a') as wstream:

        if wstream.writable():
            wstream.writelines(data)
        else:
            print("没有权限!")

用户登录函数:


def login():
    print("欢迎来到图书管理系统登录页面~")
    tips = input("是否已经注册?(yes/no)")
    if tips == 'yes':
        while True:
            username = input("输入用户名:")
            password = input("输入密码:")

            try:

                with open(path, 'rb') as stream:

                    result = stream.readlines()

                    uesr_list = [i.decode() for i in result]

                    for i in uesr_list:
                        info = i.split('   ')
                        print(info)
                        if username == info[0] and password == info[2].rstrip('\r\n'):
                            print("登录成功")
                            operate(book_path, username)
                            break
                    else:
                        print(info[0])
                        print(info[2])
                        raise Exception("用户名或密码错误,请重新输入!")

            except Exception as err:
                print(err)

            else:
                break
    else:
        print("您还未注册,请先注册后再登录!")

        logon()

查阅图书函数:


def find_books(path):
    try:
        with open(path, 'r') as rstream:

            container = rstream.readlines()

            new_container = [books_name.rstrip('\n') for books_name in container]
            for b_name in new_container:

                print("《{}》".format(b_name))

    except Exception as err:
        print("错误原因:", err)

添加图书函数:


def add_book(b_path, username):

    permission(b_path, username)

    with open(b_path, 'a') as wstream:

        if wstream.writable:
            msg = input("请输入书名:")
            try:

                with open(b_path) as rstream:
                    while True:
                        line = rstream.readline()

                        line = line.rstrip('\n')

                        if not line:
                            book = '\n' + msg
                            wstream.write(book)
                            print("添加成功")
                            break
                        else:

                            if line == msg:
                                print("{}已添加,请不要重复添加哦~".format(msg))
                                break
            except Exception as err:
                print("错误原因:", err)
        else:
            print("没有权限")

修改图书函数:


def update_book(b_path, username):
    permission(b_path, username)
    try:
        with open(b_path, 'r') as rstream:
            container = rstream.read()

            container = container.split('\n')

            find_books(book_path)
            book_name = input("请输入需要修改的图书书名:")

            for i in range(len(container)):
                if book_name == container[i]:
                    rbook_name = input("请输入修改后的图书书名:")
                    container[i] = rbook_name + '\n'
                else:

                    container[i] = container[i] + '\n'

            with open(b_path, 'w') as wwstream:
                wwstream.writelines(container)
            print("修改成功")
    except Exception as err:
        print("错误原因:", err)

删除图书函数:


def del_book(b_path, username):
    permission(path, username)
    try:
        with open(b_path, 'r') as rstream:
            container = rstream.read()

            container = container.split('\n')

            find_books(book_path)
            book_name = input("请输入需要删除的图书书名:")

            for i in range(len(container) - 1):
                if book_name == container[i]:
                    container.remove(container[i])
                else:

                    container[i] = container[i] + '\n'

            with open(b_path, 'w') as wwstream:
                wwstream.writelines(container)
            print("删除成功")
    except Exception as err:
        print("错误原因:", err)

以上函数需要有管理员操作权限;
借阅图书函数:


def borrow_book(username):
    while True:
        print("图书列表:")
        find_books(book_path)
        borrow_books = input("请选择图书:")
        try:
            with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt') as rstream:

                lines = rstream.readline()
                lines = lines.rstrip('\n')

                lines = lines.split(' ')

                if borrow_books not in lines:

                    if username in lines:
                        with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt', 'a') as wstream:

                            if borrow_books not in lines:
                                wstream.write(' {}'.format(borrow_books))
                                print("借书成功")
                                break
                            else:
                                print("您已借过此书,请从新选择!")
                                break
                    else:

                        with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt', 'a') as wstream:
                            wstream.write('\n{} {}\n'.format(username, borrow_books))
                            print("借书成功")
                            break
                else:
                    print("<>已被用户{}借走,请重新选择~".format(borrow_books, lines[0]))
        except Exception as err:
            print("错误原因:", err)

归还图书函数:


def return_book(username):
    try:
        with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt') as rstream:

            lines = rstream.readlines()

            for i in range(len(lines)):

                lines[i] = lines[i].rstrip('\n')
                lines[i] = lines[i].rstrip(' ')
                lines[i] = lines[i].split(' ')
                for ii in range(len(lines[i]) - 1):

                    if username == lines[i][0]:
                        print("{}您已借阅,未归还图书如下:".format(username))
                        print(lines[i][ii + 1])
                        msg = input("请选择你要归还的图书:")
                        with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt') as rstream:
                            lines = rstream.readlines()
                            for i in range(len(lines)):
                                if username in lines[i] and msg in lines[i]:

                                    lines[i] = lines[i].replace(msg, '')
                                    with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt', 'w') as wstream:

                                        wstream.writelines(lines)
                                        print("归还成功!")
                                        break

                            with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt') as rstream:
                                lines = rstream.readlines()
                                for i in range(len(lines)):
                                    lines[i] = lines[i].rstrip('\n')
                                    lines[i] = lines[i].rstrip(' ')
                                    lines[i] = lines[i].split(' ')

                                    for ii in range(len(lines[i])):

                                        if username == lines[i][0] and len(lines[i]) == 1:
                                            lines[i][0] = lines[i][0].replace(lines[i][0], '')
                                            lines.append(lines[i][0])

                                str = ''
                                for i in range(len(lines)):
                                    for ii in range(len(lines[i])):

                                        str += lines[i][ii] + ' '
                                    str += '\n'

                                lines.clear()
                                lines.append(str)

                                with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt', 'w') as wstream:
                                    wstream.writelines(lines)
                    else:
                        print("您还没有借阅记录哦~")

    except Exception as err:
        print("错误原因:", err)

个人信息修改:


def look_person_info(path, username):
    with open(path) as rstream:
        lines = rstream.readlines()

        for info in lines:

            info = info.split('   ')

            if username in info:
                print("----个人信息----")
                print("用户名:", info[0])
                print("邮箱:", info[1])
                print("密码:", info[2].rstrip(' '))

def update_password(path, username):
    tips = input("请选择操作:\n 1.修改邮箱\n 2.修改密码\n")

    if tips == '1':
        new_email = ''
        line = []
        try:
            with open(path) as rstream:
                while True:
                    line = rstream.readline()
                    if not line:
                        break
                    line = line.split('   ')

                    line[2] = line[2].rstrip('\n')
                    if username == line[0]:
                        new_email = input("请输入新邮箱:")
                        line[1] = new_email
                        break
        except Exception as err:
            print(err)

        else:

            with open(path, 'a') as wstream:
                for i in range(len(line)):
                    if i == 0:

                        line[i] = '\n' + line[i] + '   '
                    else:
                        line[i] = line[i] + '   '
                wstream.writelines(line)
                print("修改成功")

            with open(path) as rstream:

                lines = rstream.readlines()
                i = 0
                l = len(lines)
                while i < l:

                    if username in lines[i] and new_email not in lines[i]:
                        lines.remove(lines[i])
                    i += 1
                    l -= 1

                with open(path, 'w') as wstream:
                    wstream.writelines(lines)

    elif tips == '2':
        new_password = ''
        line = []
        try:
            with open(path) as rstream:
                while True:
                    line = rstream.readline()
                    if not line:
                        break
                    line = line.split('   ')

                    line[2] = line[2].rstrip('\n')
                    if username == line[0]:
                        new_password = input("请输入新密码:")

                        if new_password == line[2]:

                            raise Exception("新密码不能与旧密码相同哦~")
                        else:
                            line[2] = new_password
                            break

        except Exception as err:
            print(err)

        else:

            with open(path, 'a') as wstream:
                for i in range(len(line)):
                    if i == 0:

                        line[i] = '\n' + line[i] + '   '
                    else:
                        line[i] = line[i] + '   '
                wstream.writelines(line)
                print("修改成功")

            with open(path) as rstream:

                lines = rstream.readlines()
                i = 0
                l = len(lines)
                while i < l:

                    if username in lines[i] and new_password not in lines[i]:
                        lines.remove(lines[i])
                    i += 1
                    l -= 1

                with open(path, 'w') as wstream:
                    wstream.writelines(lines)

普通用户信息:


def person_information(path, username):
    tips = input("请选择操作:\n 1.查看个人信息\n 2.修改个人信息\n")
    if tips == '1':
        look_person_info(path, username)
    elif tips == '2':
        update_password(path, username)

只有管理员可执行:


user_path = r'C:\Users\ASUS\Desktop\2021课程\python\book.txt'
def permission(user_path, username):
    try:
        with open(user_path) as rstream:
            while True:
                line = rstream.readline()

                if not line:
                    break

                line = line.split('   ')

                for i in range(len(line)):
                    line[i] = line[i].rstrip('\n')

                if username == 'adm':
                    pass
                else:
                    print("只有管理员adm才可以进行该操作~")

                    operate(path, username)
    except Exception as err:
        print("错误原因:", err)

主操作界面:


book_path = r'C:\Users\ASUS\Desktop\2021课程\python\book.txt'

def operate(b_path,username):
    if username == 'adm':
        while True:
            msg = input("请选择操作:\n 1.查询图书\n 2.添加图书\n 3.修改图书\n 4.删除图书\n 5.借书\n 6.归还图书\n 7.个人信息\n 8.退出登录\n")

            if msg =='1':
                find_books(book_path)

            elif msg =='2':
                add_book(b_path, username)

            elif msg =='3':
                update_book(b_path, username)

            elif msg =='4':
                del_book(b_path, username)

            elif msg =='5':
                borrow_book(username)

            elif msg =='6':
                return_book(username)

            elif msg =='7':
                person_information(path, username)

            elif msg =='8':
                msg = input("确定退出登录吗?(yes)")
                if msg == 'yes':
                    break
            else:
                print("无效操作")
    else:
        while True:
            msg = input("请选择操作:\n 1.查询图书\n 2.借书\n 3.归还图书\n 4.个人信息\n 5.退出登录\n")

            if msg =='1':
                find_books(book_path)

            elif msg =='2':
                borrow_book(username)

            elif msg =='3':
                return_book(username)

            elif msg =='4':
                person_information(path, username)

            elif msg =='5':
                msg = input("确定退出登录吗?(yes)")
                if msg == 'yes':
                    break
            else:
                print("无效操作")

login()

完整代码:


def logon():
    print("欢迎来到图书管理系统注册页面~")
    username = input("请输入用户名:")
    if len(username) < 6:
        print("用户名不能小于6个字符")
    else:
        email = input("请输入邮箱:")
        password = input("请输入密码:")
        if len(password) < 8:
            print("密码不能少于8位")
        else:
            rpassword = input("请确认密码:")
            if password == rpassword:
                print("注册成功!")

                preserve_data(path, [username, '   ' + email, '   ' + password + '\n'])
                login_tips = input('是否登录?(yes/no)')
                if login_tips == 'yes':
                    login()
                else:
                    pass
                return True
            else:
                print("两次输入的密码不一致,请重新输入!")

                logon()

path = r'C:\Users\ASUS\Desktop\2021课程\python\User.txt'

def preserve_data(file_path, data):

    with open(file_path, 'a') as wstream:

        if wstream.writable():
            wstream.writelines(data)
        else:
            print("没有权限!")

def login():
    print("欢迎来到图书管理系统登录页面~")
    tips = input("是否已经注册?(yes/no)")
    if tips == 'yes':
        while True:
            username = input("输入用户名:")
            password = input("输入密码:")

            try:

                with open(path, 'rb') as stream:

                    result = stream.readlines()

                    uesr_list = [i.decode() for i in result]

                    for i in uesr_list:
                        info = i.split('   ')
                        print(info)
                        if username == info[0] and password == info[2].rstrip('\r\n'):
                            print("登录成功")
                            operate(book_path, username)
                            break
                    else:
                        print(info[0])
                        print(info[2])
                        raise Exception("用户名或密码错误,请重新输入!")

            except Exception as err:
                print(err)

            else:
                break
    else:
        print("您还未注册,请先注册后再登录!")

        logon()

def find_books(path):
    try:
        with open(path, 'r') as rstream:

            container = rstream.readlines()

            new_container = [books_name.rstrip('\n') for books_name in container]
            for b_name in new_container:

                print("《{}》".format(b_name))

    except Exception as err:
        print("错误原因:", err)

def add_book(b_path, username):

    permission(b_path, username)

    with open(b_path, 'a') as wstream:

        if wstream.writable:
            msg = input("请输入书名:")
            try:

                with open(b_path) as rstream:
                    while True:
                        line = rstream.readline()

                        line = line.rstrip('\n')

                        if not line:
                            book = '\n' + msg
                            wstream.write(book)
                            print("添加成功")
                            break
                        else:

                            if line == msg:
                                print("{}已添加,请不要重复添加哦~".format(msg))
                                break
            except Exception as err:
                print("错误原因:", err)
        else:
            print("没有权限")

def update_book(b_path, username):
    permission(b_path, username)
    try:
        with open(b_path, 'r') as rstream:
            container = rstream.read()

            container = container.split('\n')

            find_books(book_path)
            book_name = input("请输入需要修改的图书书名:")

            for i in range(len(container)):
                if book_name == container[i]:
                    rbook_name = input("请输入修改后的图书书名:")
                    container[i] = rbook_name + '\n'
                else:

                    container[i] = container[i] + '\n'

            with open(b_path, 'w') as wwstream:
                wwstream.writelines(container)
            print("修改成功")
    except Exception as err:
        print("错误原因:", err)

def del_book(b_path, username):
    permission(path, username)
    try:
        with open(b_path, 'r') as rstream:
            container = rstream.read()

            container = container.split('\n')

            find_books(book_path)
            book_name = input("请输入需要删除的图书书名:")

            for i in range(len(container) - 1):
                if book_name == container[i]:
                    container.remove(container[i])
                else:

                    container[i] = container[i] + '\n'

            with open(b_path, 'w') as wwstream:
                wwstream.writelines(container)
            print("删除成功")
    except Exception as err:
        print("错误原因:", err)

def borrow_book(username):
    while True:
        print("图书列表:")
        find_books(book_path)
        borrow_books = input("请选择图书:")
        try:
            with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt') as rstream:

                lines = rstream.readline()
                lines = lines.rstrip('\n')

                lines = lines.split(' ')

                if borrow_books not in lines:

                    if username in lines:
                        with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt', 'a') as wstream:

                            if borrow_books not in lines:
                                wstream.write(' {}'.format(borrow_books))
                                print("借书成功")
                                break
                            else:
                                print("您已借过此书,请从新选择!")
                                break
                    else:

                        with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt', 'a') as wstream:
                            wstream.write('\n{} {}\n'.format(username, borrow_books))
                            print("借书成功")
                            break
                else:
                    print("<>已被用户{}借走,请重新选择~".format(borrow_books, lines[0]))
        except Exception as err:
            print("错误原因:", err)

def return_book(username):
    try:
        with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt') as rstream:

            lines = rstream.readlines()

            for i in range(len(lines)):

                lines[i] = lines[i].rstrip('\n')
                lines[i] = lines[i].rstrip(' ')
                lines[i] = lines[i].split(' ')
                for ii in range(len(lines[i]) - 1):

                    if username == lines[i][0]:
                        print("{}您已借阅,未归还图书如下:".format(username))
                        print(lines[i][ii + 1])
                        msg = input("请选择你要归还的图书:")
                        with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt') as rstream:
                            lines = rstream.readlines()
                            for i in range(len(lines)):
                                if username in lines[i] and msg in lines[i]:

                                    lines[i] = lines[i].replace(msg, '')
                                    with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt', 'w') as wstream:

                                        wstream.writelines(lines)
                                        print("归还成功!")
                                        break

                            with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt') as rstream:
                                lines = rstream.readlines()
                                for i in range(len(lines)):
                                    lines[i] = lines[i].rstrip('\n')
                                    lines[i] = lines[i].rstrip(' ')
                                    lines[i] = lines[i].split(' ')

                                    for ii in range(len(lines[i])):

                                        if username == lines[i][0] and len(lines[i]) == 1:
                                            lines[i][0] = lines[i][0].replace(lines[i][0], '')
                                            lines.append(lines[i][0])

                                str = ''
                                for i in range(len(lines)):
                                    for ii in range(len(lines[i])):

                                        str += lines[i][ii] + ' '
                                    str += '\n'

                                lines.clear()
                                lines.append(str)

                                with open(r'C:\Users\ASUS\Desktop\2021课程\python\user_book.txt', 'w') as wstream:
                                    wstream.writelines(lines)
                    else:
                        print("您还没有借阅记录哦~")

    except Exception as err:
        print("错误原因:", err)

def look_person_info(path, username):
    with open(path) as rstream:
        lines = rstream.readlines()

        for info in lines:

            info = info.split('   ')

            if username in info:
                print("----个人信息----")
                print("用户名:", info[0])
                print("邮箱:", info[1])
                print("密码:", info[2].rstrip(' '))

def update_password(path, username):
    tips = input("请选择操作:\n 1.修改邮箱\n 2.修改密码\n")

    if tips == '1':
        new_email = ''
        line = []
        try:
            with open(path) as rstream:
                while True:
                    line = rstream.readline()
                    if not line:
                        break
                    line = line.split('   ')

                    line[2] = line[2].rstrip('\n')
                    if username == line[0]:
                        new_email = input("请输入新邮箱:")
                        line[1] = new_email
                        break
        except Exception as err:
            print(err)

        else:

            with open(path, 'a') as wstream:
                for i in range(len(line)):
                    if i == 0:

                        line[i] = '\n' + line[i] + '   '
                    else:
                        line[i] = line[i] + '   '
                wstream.writelines(line)
                print("修改成功")

            with open(path) as rstream:

                lines = rstream.readlines()
                i = 0
                l = len(lines)
                while i < l:

                    if username in lines[i] and new_email not in lines[i]:
                        lines.remove(lines[i])
                    i += 1
                    l -= 1

                with open(path, 'w') as wstream:
                    wstream.writelines(lines)

    elif tips == '2':
        new_password = ''
        line = []
        try:
            with open(path) as rstream:
                while True:
                    line = rstream.readline()
                    if not line:
                        break
                    line = line.split('   ')

                    line[2] = line[2].rstrip('\n')
                    if username == line[0]:
                        new_password = input("请输入新密码:")

                        if new_password == line[2]:

                            raise Exception("新密码不能与旧密码相同哦~")
                        else:
                            line[2] = new_password
                            break

        except Exception as err:
            print(err)

        else:

            with open(path, 'a') as wstream:
                for i in range(len(line)):
                    if i == 0:

                        line[i] = '\n' + line[i] + '   '
                    else:
                        line[i] = line[i] + '   '
                wstream.writelines(line)
                print("修改成功")

            with open(path) as rstream:

                lines = rstream.readlines()
                i = 0
                l = len(lines)
                while i < l:

                    if username in lines[i] and new_password not in lines[i]:
                        lines.remove(lines[i])
                    i += 1
                    l -= 1

                with open(path, 'w') as wstream:
                    wstream.writelines(lines)

def person_information(path, username):
    tips = input("请选择操作:\n 1.查看个人信息\n 2.修改个人信息\n")
    if tips == '1':
        look_person_info(path, username)
    elif tips == '2':
        update_password(path, username)

user_path = r'C:\Users\ASUS\Desktop\2021课程\python\book.txt'
def permission(user_path, username):
    try:
        with open(user_path) as rstream:
            while True:
                line = rstream.readline()

                if not line:
                    break

                line = line.split('   ')

                for i in range(len(line)):
                    line[i] = line[i].rstrip('\n')

                if username == 'adm':
                    pass
                else:
                    print("只有管理adm才可以进行该操作~")

                    operate(path, username)
    except Exception as err:
        print("错误原因:", err)

book_path = r'C:\Users\ASUS\Desktop\2021课程\python\book.txt'

def operate(b_path,username):
    if username == 'adm':
        while True:
            msg = input("请选择操作:\n 1.查询图书\n 2.添加图书\n 3.修改图书\n 4.删除图书\n 5.借书\n 6.归还图书\n 7.个人信息\n 8.退出登录\n")

            if msg =='1':
                find_books(book_path)

            elif msg =='2':
                add_book(b_path, username)

            elif msg =='3':
                update_book(b_path, username)

            elif msg =='4':
                del_book(b_path, username)

            elif msg =='5':
                borrow_book(username)

            elif msg =='6':
                return_book(username)

            elif msg =='7':
                person_information(path, username)

            elif msg =='8':
                msg = input("确定退出登录吗?(yes)")
                if msg == 'yes':
                    break
            else:
                print("无效操作")
    else:
        while True:
            msg = input("请选择操作:\n 1.查询图书\n 2.借书\n 3.归还图书\n 4.个人信息\n 5.退出登录\n")

            if msg =='1':
                find_books(book_path)

            elif msg =='2':
                borrow_book(username)

            elif msg =='3':
                return_book(username)

            elif msg =='4':
                person_information(path, username)

            elif msg =='5':
                msg = input("确定退出登录吗?(yes)")
                if msg == 'yes':
                    break
            else:
                print("无效操作")

login()

注:
1.文件读取路径各有差异,需要进行修改;
2.管理员身份需要在函数模块内修改,注册时且仅有一个。
3.建议运行环境使用pycharm.

以上为本次分享的全部内容感谢大家的支持,欢迎留言评论。

Original: https://blog.csdn.net/m0_46228023/article/details/117961898
Author: 油饼包烧麦
Title: python实现图书管理系统

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/671037/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球