python實現圖書管理系統——通過excel檔案或者TXT檔案存放資料

YoungKey_Xie發表於2020-10-28

用python實現圖書管理系統——通過excel檔案或者TXT檔案存放資料

話不多說,先上圖,看看執行起來的效果:
執行效果圖由上圖可知,我實現的主要功能:

  1. 使用者註冊
  2. 使用者登入
  3. 新增圖書
  4. 查詢圖書
  5. 刪除圖書
  6. 修改圖書資訊
  7. 觀看所有圖書資訊
    接下來詳細介紹每個功能如何實現:
    (這裡,我分別用了兩種方法實現對資料的運用)
    在整個程式之前我先宣告瞭兩個全域性變數,用於設立字典列表,分別存放使用者資訊和書籍資訊:
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("\nname\t"+input_name+"\tpasswd\t"+input_passwd+"\tstate\t1\tcount\t3")
        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( "\nbookName\t" + input_bookName + "\tbookID\t" + bookID + "\tauthor\t" + 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 = 'bookName\t'+bookName_Input+'\tbookID\t'+book['bookID']+'\tauthor\t'+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)

總結

整個圖書管理系統體現的是對字典列表和檔案讀寫方面的操作。如何能夠更恰當的把資料增刪改查,是這個系統的重點。

宣告:本文轉載需註明出處。若有疑問或需要全部程式碼,可私信本人。

相關文章