1. 程式人生 > 程式設計 >Python使用檔案操作實現一個XX資訊管理系統的示例

Python使用檔案操作實現一個XX資訊管理系統的示例

寫在前面

大家好,我是第一次python學了一個學期,期末要完成一個畢業生資訊管理系統大作業的小韓了,由於上次沒有仔細看開發實現的要求,實現了一個簡單的畢業生資訊管理系統,而這次專門整理了兩種使用檔案進行儲存資料實現的畢業生資訊管理系統,因為是第一次學python,還不太熟悉python的寫法, 而之前是學 c 、c++,感覺我的這個寫的有一股 c/c++的內味:

1. 使用excel .xlsx 儲存資料實現一個畢業生資訊管理系統2. 使用文字文件.txt儲存資料實現一個畢業生資訊管理系統

以下將會在程式碼進行詳細的介紹

一、 對excel表格操作實現一個畢業生資訊管理系統

開發要求

1. 採用 python 語言實現一個XX資訊管理系統

2.實現基本的增刪改查的基本功能,還可以加上一些如排序,搜尋的操作3. 採用檔案儲存資料(而不是每次從鍵盤輸入)

4. 各個功能介面迴圈呼叫環境以及

開發軟體

1. python 3.7.0 版本

2. pycharm 2019 中文版

一、 函式模組設計:

1.主函式模組

實現功能

  • 查詢搜尋畢業生資訊列表
  • 增加畢業生資訊
  • 修改畢業生資訊
  • 刪除畢業生資訊
  • 畢業生資訊排序
  • 退出畢業生資訊管理系統
def main(): # 主函式
  arry = [0,1,2,3,4,5] # 定義一個選項的列表 用於輸入判斷
  Menu() # 先列印選單
  while 1:
    a = input("請輸入: ")
    if a.isdigit() and int(a) in arry: # 這裡判斷輸入的是不是數字 且在不在選項的列表中 如果輸入合法再進行功能呼叫
      a = int(a)
      while a:
        if a == 1:
          PrintStudentList() # 查詢搜尋畢業生資訊功能
          Menu()
          break
        if a == 2:
          AddStudent() # 新增畢業生資訊功能
          Menu()
          break
        if a == 3:
          ChangeStudent() # 修改畢業生資訊功能
          Menu()
          break
        if a == 4:
          DeleteStudent() # 刪除畢業生資訊功能
          Menu()
          break
        if a == 5:
          SortData() # 畢業生資訊排序功能
          Menu()
          break
        elif a > 5 or a < 0:
          print("輸入有誤!")
          break

      if a == 0: # 按0退出該畢業生資訊管理系統
        print("系統已退出!")
        exit()
    else:
      print("請輸入0--5!")


main()

這裡因為還沒有學到python中的字典那部分知識,而pyhton中又沒有switch和case所以就使用這個 if 進行判斷 雖然比較繁瑣,但是看起來還是比較清晰易懂的

二、 資料檔案設計

因為這裡要採用檔案進行儲存資料,我第一個想到的就是excel表格,這種.xlsx檔案儲存資料一目瞭然,因此本次選擇了excel表格進行資料儲存,寫入,讀取,修改,刪除等基本功能

主要資訊:

本次實現的是一個畢業生資訊管理系統,因此給每個畢業生設計的個人資訊如下:
學號 姓名 電話 年級 學院 就業 就業公司 郵箱 月薪

Python使用檔案操作實現一個XX資訊管理系統的示例

關於對excel 表格使用則需要匯入兩個包:

from openpyxl import Workbook # 匯入操作 excel時所用的庫
from openpyxl import load_workbook # 用於對本地已經存在的excel檔案操作

如果這裡匯入失敗的話,可能需要自己手動進行 openpyxl 的下載 下載方法具體如下

點選 檔案 -->> 點選設定(setting) -->> 點選自己的專案 -->> 點選第一個選項 -->> 點選頁面的右側的加號 -->> 輸入 想要匯入的包 (openpyxl) -->> 點選左下角的 install Package 稍等一會即可完成安裝

Python使用檔案操作實現一個XX資訊管理系統的示例

2.增加畢業生資訊模組

從鍵盤獲取輸入的資訊,資訊校驗成功後,先將資訊儲存在一個列表中,然後最後將整個列表插入到excel表格中,然後儲存,這樣方便寫入,否則頻繁的開啟關閉檔案比較繁瑣,容易出現錯誤。
例如:下面插入 學號 id

先建立一個空的列表 然後先對學號進行校驗,首先校驗學號是否合法,比如長度要求,或者插入的是否和表中的是否重複,當校驗成功後才將學號儲存到 列表中

 r = [] # 建立一個新的列表 在將這個列表插入到excel表中
  ID = None
  wb = load_workbook('StudentList.xlsx')
  sheet = wb.active
  id = input("請輸入學號:")
  if CheckIdIsRight(id):
    while 1:
      id = input("請輸入正確的學號!")
      if not CheckIdIsRight(id):
        ID = id
        break
  else:
    ID = id
  r.append(ID) # 將輸入的ID插入到列表中

其餘的其他資訊依次類推
最後將整個列表插入到excel表格中,然後關閉並儲存檔案

 sheet.append(r) # 將整個列表插入到excel 表格中 即為插入一行資料
  wb.close()
  wb.save('StudentList.xlsx')

3. 查詢搜尋畢業生資訊模組

Python使用檔案操作實現一個XX資訊管理系統的示例

該功能主要實現查詢和搜尋的功能 ,比如檢視所有資訊列表 ,按相關資訊查詢畢業生資訊,
例如:查詢所有畢業生資訊:

def PrintAll():
  wb = load_workbook('StudentList.xlsx') # 開啟現在已經有的表
  sheet = wb.active # 獲取當前活躍的表 也就是當前使用的表
  for row in sheet.rows: # 迴圈每一行
    for cell in row: # 迴圈每一行的單元格
      print(cell.value,end="   ") # 打印出每一個單元格的資料
    print()
  print()

只需要將每一個單元格的按順序打印出來即可

例如:按學號查詢該畢業生的資訊

 def SelectById():
    id = input("請輸入需要查詢的學號:")
    if id.isdigit() and not CheckIdIsRight(id):
      id1 = int(id) # 將輸入的str型別的轉換為 int 型別
      wb = load_workbook('StudentList.xlsx') # 開啟現在已經有的表
      sheet = wb.active # 獲取當前活躍的表 也就是當前使用的表
      r = FindId(id1)
      for i in range(1,10):
        print(sheet.cell(1,i).value,end="  ") # 打印出表頭的資訊
      print()
      for i in range(1,10):
        print(sheet.cell(r,end="  ") # 打印出該id對應的資訊
      print()
    else:
      print("學號輸入錯誤!")

首先應該判斷一下輸入的學號是不是一串數字,而且 想要查詢的學生的學號是存在的,因為我們這裡規定學號應該是類似於1700000000 這樣的一個數字,而python預設 input 輸入的是一個 str 字串型別的 所以這裡防止輸入錯誤導致程式崩潰 因此加入了一些校驗,當確認合法之後 再將其 轉換為 int 型別的變數 進行使用。
而具體的就是通過一個findid的函式來返回學號所在的行 這樣就可以將這一行的資訊打印出來即可 ,列印學生資訊的同時不要忘了打印表頭的資訊,這樣看起來會更加的清晰。

4. 修改畢業生資訊模組

Python使用檔案操作實現一個XX資訊管理系統的示例

在修改該學生資訊之前,同樣對其輸入的學號進行校驗,校驗完成之後進行相關資訊的修改
修改的基本方法就是,通過學號找到該學生所在的行,然後對特定的列的資訊修改(直接賦值),最後儲存到檔案即可
例如 : 修改姓名

def changename(row,wb): # 修改姓名 # row 為其所在的資訊的行 wb 是表格物件
    name = input("請輸入修改之後的名字:")
    sheet.cell(row,name)
    wb.save('StudentList.xlsx')

5. 畢業生資訊排序

Python使用檔案操作實現一個XX資訊管理系統的示例

這裡排序主要使用了一個氣泡排序的演算法 對資料進行排序,雖然python中是有內建的排序算髮法的,但是我這裡還是自己實現了一個排序(升序),排完序了之後 也可以對升序的進行一個反轉 得到一個降序的列表。 因為是對某一項的單一資料進行排序,而排序結果是要求打印出所有資訊的,因此先得到一個某一項資料排好序的列表,然後將列表對應的資訊進行列印即可。
例如: 按學號進行排序
氣泡排序:

def BubbleSort(l2): # 氣泡排序對列表中的資料進行一個升序的排列
  for i in range(0,len(l2)):
    count = 0
    for j in range(1,len(l2)-i):
      if int(l2[j - 1]) > int(l2[j]):
        temp = l2[j]
        l2[j] = l2[j - 1]
        l2[j - 1] = temp
        count = count + 1
    if count == 0: # 演算法優點 當已經有序時就不再進行排序
      return l2
  return l2 # 返回排好序的 列表

按學號從小到大排序並列印學生資訊

def GetAllStudentById(): # 按學號排序打印出學生資訊(升序)
  l = [] # 建立一個空的列表
  wb = load_workbook('StudentList.xlsx')
  sheet = wb.active
  for column in list(sheet.columns)[0]:
    l.append(column.value) # 將學號插入到列表中 得到一個學號列表
  l2 = l[1:] # 由於第一個是表頭 將第二個位置以後的範圍 拷貝給 l2
  l3 = BubbleSort(l2) # 進行 學號排序
  # 3 是排好序的列表
  for i in range(1,10):
    print(sheet.cell(1,end="   ") # 打印出表頭的資訊
  print()
  for i in range(0,len(l3)): # 依次找到排好序的學號或年級對應的學生資訊即可
    r = FindId(l3[i]) # 找到該行
    for j in range(1,10):
      print(sheet.cell(r,j).value,end="    ") # 打印出該id對應的資訊
    print()

注意 :因為學號是唯一的,因此可以通過找道該行,然後通過行號進行某一行的定向資訊列印,但是像年級 ,月薪資訊是有可能重複的,就不能再像學號一樣查詢,列印了,但是我們可以先將年級的列表排好序,然後進行一個去重,這樣,就可以將符合滿足,排好序的年級列表中的年級對應的學生,資訊全部打印出來

6. 刪除畢業生資訊

非常簡單,只需要將要刪除的學生的學號輸入,然後學號校驗合法且存在之後,找到對應的該行,然後將這一行的資料刪除就可以了。

def DeleteStudent(): # 刪除學生資訊
  PrintAll()
  id = input("請輸入要刪除學生的學號:")
  if not CheckIdIsRight(id): # 判斷學號為id的學生是否在StudentList.xlsx中
    print("學號正確!")
    id = int(id)
    row = FindId(id) # 查詢其所在的行
    wb = load_workbook('StudentList.xlsx')
    sheet = wb.active
    isdelete = input("是否刪除該學生資訊?輸入是或否:")
    if isdelete == '是':
      sheet.delete_rows(row,1) # 刪除該行
      wb.save('StudentList.xlsx')
      print("刪除成功!")
    else:
      print("刪除失敗!")

  else:
    print("學號輸入錯誤!")

三、 測試

1. 查詢搜尋測試

Python使用檔案操作實現一個XX資訊管理系統的示例

Python使用檔案操作實現一個XX資訊管理系統的示例

Python使用檔案操作實現一個XX資訊管理系統的示例

Python使用檔案操作實現一個XX資訊管理系統的示例

2. 新增測試

Python使用檔案操作實現一個XX資訊管理系統的示例

3.修改測試

Python使用檔案操作實現一個XX資訊管理系統的示例

4. 資訊排序測試

Python使用檔案操作實現一個XX資訊管理系統的示例

Python使用檔案操作實現一個XX資訊管理系統的示例

Python使用檔案操作實現一個XX資訊管理系統的示例

5. 刪除資訊測試

Python使用檔案操作實現一個XX資訊管理系統的示例

Python使用檔案操作實現一個XX資訊管理系統的示例

Python使用檔案操作實現一個XX資訊管理系統的示例

四、 原始碼

from openpyxl import Workbook # 匯入操作 excel時所用的庫
from openpyxl import load_workbook

IsJob = ['是','否']


def Menu(): # 選單主介面
  print(end=" " * 45)
  print('*' * 22)
  print(end=" " * 45)
  print("* 查詢畢業生資訊輸入: 1 *")
  print(end=" " * 45)
  print("* 新增畢業生資訊輸入: 2 *")
  print(end=" " * 45)
  print("* 修改畢業生資訊輸入: 3 *")
  print(end=" " * 45)
  print("* 刪除畢業生資訊輸入: 4 *")
  print(end=" " * 45)
  print("* 檢視排序統計請輸入: 5 *")
  print(end=" " * 45)
  print("* 退出系統請輸入:  0 *")
  print(end=" " * 45)
  print('*' * 22)


def SelectStudentMenu():
  print(end=" " * 45)
  print('*' * 25)
  print(end=" " * 45)
  print("* 檢視所有資訊請輸入:  1 *")
  print(end=" " * 45)
  print("* 按學號查詢資訊輸入:  2 *")
  print(end=" " * 45)
  print("* 按年級查詢資訊輸入:  3 *")
  print(end=" " * 45)
  print("* 按是否就業查詢輸入:  4 *")
  print(end=" " * 45)
  print("* 退出查詢功能請輸入:  0 *")
  print(end=" " * 45)
  print('*' * 25)


def FindId(id): # 在excel中找到該 id 所在的行 返回行數
  i = 0
  wb = load_workbook('StudentList.xlsx')
  sheet = wb.active
  for column in list(sheet.columns)[0]: # 迴圈學號那一列的資料
    i = i + 1
    if id == column.value: # 找到了返回
      return i # 返回行數


def BubbleSort(l2): # 氣泡排序對列表中的資料進行一個升序的排列
  for i in range(0,len(l2)):
      if int(l2[j - 1]) > int(l2[j]):
        temp = l2[j]
        l2[j] = l2[j - 1]
        l2[j - 1] = temp
        count = count + 1
    if count == 0: # 演算法優點 當已經有序時就不再進行排序
      return l2
  return l2 # 返回排好序的 列表


def GetAllStudentByGadeOrMoney(x):
  l = [] # 建立一個空的列表 用於存放資料進行排序
  wb = load_workbook('StudentList.xlsx')
  sheet = wb.active
  for column in list(sheet.columns)[x]:
    l.append(column.value) # 將薪資或年級插入到列表中 得到一個薪資或年級列表
  l2 = l[1:] # 由於第一個是表頭 將第二個位置以後的範圍 拷貝給 l2
  l3 = BubbleSort(l2) # 進行 薪資或年級排序   # 3 是排好序的列表
  i = 1
  l3.reverse() # 進行一個反轉列表 得到一個降序的列表
  while i < len(l3): # 這是為了剔除列表中相同的元素
    if l3[i] == l3[i - 1]:
      del l3[i - 1]
    else:
      i = i + 1
  for i in range(1,end="   ") # 打印出表頭的資訊
  print()
  j = 0
  while j < len(l3): # 按照排好序的列表對應的值 在excel中查詢 打印出對應的資訊
    for row in sheet.rows: # 迴圈每一行
      for cell in row: # 迴圈每一行的單元格
        if cell.value == l3[j]: # 找到年級符合的學生的資訊
          for cell in row:
            print(cell.value,end="    ") # 打印出這一行的資訊
          print()
    j = j + 1
  print()


def GetAllStudentById(): # 按學號排序打印出學生資訊(升序)
  l = [] # 建立一個空的列表
  wb = load_workbook('StudentList.xlsx')
  sheet = wb.active
  for column in list(sheet.columns)[0]:
    l.append(column.value) # 將學號插入到列表中 得到一個學號列表
  l2 = l[1:] # 由於第一個是表頭 將第二個位置以後的範圍 拷貝給 l2
  l3 = BubbleSort(l2) # 進行 學號排序
  # 3 是排好序的列表
  for i in range(1,end="    ") # 打印出該id對應的資訊
    print()


def PrintAll():
  wb = load_workbook('StudentList.xlsx') # 開啟現在已經有的表
  sheet = wb.active # 獲取當前活躍的表 也就是當前使用的表
  for row in sheet.rows: # 迴圈每一行
    for cell in row: # 迴圈每一行的單元格
      print(cell.value,end="   ") # 打印出每一個單元格的資料
    print()
  print()


def PrintStudentList(): # 列印excel檔案中的資料

  def SelectById():
    id = input("請輸入需要查詢的學號:")
    if id.isdigit() and not CheckIdIsRight(id):
      id1 = int(id)
      wb = load_workbook('StudentList.xlsx') # 開啟現在已經有的表
      sheet = wb.active # 獲取當前活躍的表 也就是當前使用的表
      r = FindId(id1)
      for i in range(1,end="  ") # 打印出該id對應的資訊
      print()
    else:
      print("學號輸入錯誤!")

  def SelectByGrade():
    wb = load_workbook('StudentList.xlsx') # 開啟現在已經有的表
    sheet = wb.active # 獲取當前活躍的表 也就是當前使用的表
    grade = input("請輸入要查詢的年級:")
    if grade.isdigit():
      for i in range(1,end="  ") # 打印出表頭的資訊
      print()
      # 這裡也需要進行優化
      for row in sheet.rows: # 迴圈每一行
        for cell in row: # 迴圈每一行的單元格
          if cell.value == int(grade): # 找到年級符合的學生的資訊
            for cell in row:
              print(cell.value,end="  ") # 打印出這一行的資訊
            print()
      print()
    else:
      print("輸入不合法!")

  def SelectByIsJob():
    wb = load_workbook('StudentList.xlsx') # 開啟現在已經有的表
    sheet = wb.active # 獲取當前活躍的表 也就是當前使用的表
    isjob = input("請輸入要查詢的學生是否已經就業 :")
    if isjob in IsJob: # 檢查輸入是否正確
      if isjob == '是': # 如果要查詢已經就業的學生
        for i in range(1,10):
          print(sheet.cell(1,end="  ") # 打印出表頭的資訊
        print()
        for row in sheet.rows: # 迴圈每一行
          for cell in row: # 迴圈每一行的單元格
            if cell.value == '是': # 找到就業資訊是 '是'的學生的那一行
              for cell in row:
                print(cell.value,end="  ") # 打印出這一行的資訊
              print()
        print()
      else: # 查詢 '否' 還沒有就業的學生
        for i in range(1,end="  ") # 打印出表頭的資訊
        print()
        for row in sheet.rows: # 迴圈每一行
          for cell in row: # 迴圈每一行的單元格
            if cell.value == '否': # 找到就業資訊是 '否'的學生的那一行的內容
              for cell in row:
                print(cell.value,end="  ") # 打印出這一行的資訊
              print()
        print()
    else:
      print("輸入錯誤!")

  arry = [0,4]
  while 1: # 迴圈查詢直到退出
    SelectStudentMenu()
    a = (input("請輸入想要執行的操作:"))
    if a.isdigit() and int(a) in arry:
      a = int(a)
      while a:
        if a == 1:
          PrintAll()
          break
        if a == 2:
          SelectById()
          break
        if a == 3:
          SelectByGrade()
          break
        if a == 4:
          SelectByIsJob()
          break
        if a < 0 or a > 4:
          print("輸入錯誤!請重新輸入:")
          break
      if a == 0:
        break
    else:
      print("請輸入0--4!")


def CheckIdIsRight(id1): # 檢查學號ID是否存在或格式不正確
  wb = load_workbook('StudentList.xlsx')
  sheet = wb.active
  if id1.isdigit():
    id2 = int(id1)
    for column in list(sheet.columns)[0]:
      if id2 == column.value:
        print("學號存在")
        return False
    if id2 < 1000000000 or id2 > 10000000000:
      print("學號格式不正確!")
      return True
  else:
    print("學號應該是數字!")
    return True


def AddStudent(): # 新增學生資訊模組
  r = [] # 建立一個新的列表 在將這個列表插入到excel表中
  ID = None
  wb = load_workbook('StudentList.xlsx')
  sheet = wb.active
  id = input("請輸入學號:")
  if CheckIdIsRight(id):
    while 1:
      id = input("請輸入正確的學號!")
      if not CheckIdIsRight(id):
        ID = id
        break
  else:
    ID = id
  r.append(ID) # 將輸入的ID插入到列表中
  name = input("請輸入你的名字:") # 新增姓名資訊
  r.append(name) # 將姓名插入到列表中
  tell = input("請輸入你的電話號碼:")
  while 1:
    if len(tell) != 11:
      print("電話號碼格式不正確!請重新輸入:")
      tell = input()
      if len(tell) == 11:
        print("輸入成功!")
        break
    if len(tell) == 11:
      break
  r.append(tell) # 將電話號碼插入到列表中
  grade = int(input("請輸入你的年級:")) # 新增年級資訊
  while 1:
    if grade < 2000: # 判斷年級是否正確範圍內
      print("年級輸入不正確!請重新輸入:")
      grade = int(input())
      if grade >= 2000:
        print("輸入成功!")
        break
    if grade >= 2000:
      break
  r.append(grade) # 將年級插入到列表中
  institute = input("請輸入你的學院:") # 新增學院資訊
  r.append(institute) # 將學院資訊插入到列表中
  isjob = input("是否已經工作:輸入 :是或否!") # 新增是否就業資訊 當其 是 '是'時才能新增公司
  while 1:
    if isjob in IsJob:
      r.append(isjob)
      break
    else:
      print("輸入錯誤請重新輸入:")
      isjob = input()
  if r[5] == '是': # 新增公司資訊
    company = input("請輸入你的公司名 ")
    r.append(company)
  else:
    company = '無'
    r.append(company)

  e_mail = input("請輸入你的電子郵箱:") # 新增郵箱資訊
  r.append(e_mail) # 將電子郵箱資訊插入到列表中
  if r[5] == '是':
    money = input("請輸入你的月薪:") # 新增月薪資訊
    r.append(money) # 只有當已經就業時才可以新增月薪資訊
  if r[5] == '否':
    money = 0 # 否則 月薪預設為 0
    r.append(money)
  sheet.append(r) # 將整個列表插入到excel 表格中 即為插入一行資料
  wb.close()
  wb.save('StudentList.xlsx')


def StudentPersonalMsg(): # 修改資訊介面選擇
  print(end=" " * 45)
  print('*' * 23)
  print(end=" " * 45)
  print("* 修改學生姓名請輸入: 1 *")
  print(end=" " * 45)
  print("* 修改電話號碼請輸入: 2 *")
  print(end=" " * 45)
  print("* 修改是否就業請輸入: 3 *")
  print(end=" " * 45)
  print("* 修改就業公司請輸入: 4 *")
  print(end=" " * 45)
  print("* 修改郵箱資訊請輸入: 5 *")
  print(end=" " * 45)
  print("* 修改月薪資訊請輸入: 6 *")
  print(end=" " * 45)
  print("* 退出修改請輸入:  0 *")
  print(end=" " * 45)
  print('*' * 23)


def ChangeStudent(): # 修改學生資訊模組
  def changename(row,name)
    wb.save('StudentList.xlsx')

  def changetell(row,wb): # 修改電話號碼 同樣進行資訊格式校對
    tell = input("請輸入修改後的電話號碼:")
    while 1:
      if len(tell) != 11:
        print("電話號碼格式不正確!請重新輸入:")
        tell = input()
        if len(tell) == 11:
          print("輸入成功!")
          break
      if len(tell) == 11:
        break
    sheet.cell(row,tell)
    wb.save('StudentList.xlsx')

  def changeisjob(row,wb): # 修改是否就業狀態資訊
    IsJob = ['是','否']
    isjob = input("是否已經工作:輸入 :是或否!")
    while 1:
      if isjob in IsJob:
        sheet.cell(row,6,isjob)
        wb.save('StudentList.xlsx')
        break
      else:
        print("輸入錯誤請重新輸入:")
        isjob = input()

  def changecompany(row,wb): # 修改公司資訊
    if sheet.cell(row,6).value == '是': # 判斷是否就業
      company = input("請輸入修改後的公司:")
      sheet.cell(row,7,company)
      wb.save('StudentList.xlsx')
    else:
      print("請先修改是否就業:")
      changeisjob(row,wb)
      changecompany(row,wb)

  def changemail(row,wb): # 修改學生郵箱資訊
    mail = input("請輸入修改之後的郵箱:")
    sheet.cell(row,8,mail)
    wb.save('StudentList.xlsx')

  def changemoney(row,wb): # 修改月薪資訊
    if sheet.cell(row,6).value == '是': # 判斷是否就業
      money = int(input("請輸入修改之後的月薪:"))
      sheet.cell(row,9,money)
      wb.save('StudentList.xlsx')
    else:
      print("請先修改就業狀態及就業公司!")
      changeisjob(row,wb)
      changemoney(row,wb)

  PrintAll()
  arry = [0,5,6]
  id = input("請輸入你要修改的學生的學號:")
  if not CheckIdIsRight(id): # 檢驗學號是否存在
    print("學號正確!")
    row = FindId(id)
    wb = load_workbook('StudentList.xlsx')
    sheet = wb.active
    StudentPersonalMsg()
    while 1:
      a = input("請輸入:")
      if a.isdigit() and int(a) in arry:
        a = int(a)
        while a > 0:
          if a == 1:
            changename(row,wb)
            print("修改成功!")
            break
          if a == 2:
            changetell(row,wb)
            print("修改成功!")
            break
          if a == 3:
            changeisjob(row,wb)
            print("修改成功!")
            break
          if a == 4:
            changecompany(row,wb)
            print("修改成功!")
            break
          if a == 5:
            changemail(row,wb)
            print("修改成功!")
            break
          if a == 6:
            changemoney(row,wb)
            print("修改成功!")
            break
          elif a > 6 or a < 0:
            print("輸入有誤!")
            break
        if a == 0:
          break
      else:
        print("請輸入正確的選項0--6!")
        break

  else:
    print("請輸入正確的學號!")


def DeleteStudent(): # 刪除學生資訊
  PrintAll()
  id = input("請輸入要刪除學生的學號:")
  if not CheckIdIsRight(id): # 判斷學號為id的學生是否在StudentList.xlsx中
    print("學號正確!")
    id = int(id)
    row = FindId(id) # 查詢其所在的行
    wb = load_workbook('StudentList.xlsx')
    sheet = wb.active
    isdelete = input("是否刪除該學生資訊?輸入是或否:")
    if isdelete == '是':
      sheet.delete_rows(row,1) # 刪除該行
      wb.save('StudentList.xlsx')
      print("刪除成功!")
      PrintAll()
    else:
      print("刪除失敗!")

  else:
    print("學號輸入錯誤!")


def SortMenu():
  print(end=" " * 45)
  print('*' * 30)
  print(end=" " * 45)
  print("* 按學號從小到大排序結果輸入: 1 *")
  print(end=" " * 45)
  print("* 按年級從大到小排序結果輸入: 2 *")
  print(end=" " * 45)
  print("* 按薪資從高到低排序結果輸入: 3 *")
  print(end=" " * 45)
  print("* 退出此功能請輸入:      0 *")
  print(end=" " * 45)
  print('*' * 30)


def SortData():
  SortMenu()
  arry = [0,3]
  while 1:
    a = input("請輸入: ")
    if a.isdigit() and int(a) in arry:
      a = int(a)
      while a:
        if a == 1:
          GetAllStudentById()
          SortMenu()
          break
        if a == 2:
          GetAllStudentByGadeOrMoney(3)
          SortMenu()
          break
        if a == 3:
          GetAllStudentByGadeOrMoney(8)
          SortMenu()
          break
        elif a > 3 or a < 0:
          print("輸入有誤!")
          break
      if a == 0:
        break
    else:
      print("請輸入正確的選項0--3")


def main(): # 主函式
  arry = [0,5]
  Menu() # 先列印選單
  while 1:
    a = input("請輸入: ")
    if a.isdigit() and int(a) in arry:
      a = int(a)
      while a:
        if a == 1:
          PrintStudentList()
          Menu()
          break
        if a == 2:
          AddStudent()
          Menu()
          break
        if a == 3:
          ChangeStudent()
          Menu()
          break
        if a == 4:
          DeleteStudent()
          Menu()
          break
        if a == 5:
          SortData()
          Menu()
          break
        elif a > 5 or a < 0:
          print("輸入有誤!")
          break

      if a == 0: # 按0退出程序
        print("系統已退出!")
        exit()
    else:
      print("請輸入0--5!")


main()

檔案:

Python使用檔案操作實現一個XX資訊管理系統的示例

注意:將表格excel檔案放在程式碼相同目錄下即可 ,否則應該在使用檔案時填上絕對路徑,否則會出現檔案打不開,或者找不到等錯誤,在系統執行期間應該講檔案儲存並關閉,否則當檔案處於開啟狀態時無法進行修改,插入等操作,出現錯誤。

二、 採用文字文件儲存資料實現的畢業生資訊管理系統

基本思想與上述的相似,就不再這裡闡述了,以下附上原始碼。

原始碼

StudentInfo = ['學號','姓名','性別','畢業年級','就業公司名稱','電話號碼(+86)','家庭住址']


def GetList(): # 將 StudentMsg.txt 中的資料 拷貝到一個列表中
  fiel = open('StudentMsg.txt','r',encoding='utf-8')
  l = []
  for line in fiel:
    l.append(line.strip()) # 將所有的資訊以c字元形式插入到列表中
  return l


def PrintAllMsg(): # 打印出所有的資訊
  l = GetList()
  print(StudentInfo)
  count = 0
  for i in range(0,len(l)): # 將列表中的所有資訊 按7條一行列印
 
    count = count + 1
    print(l[i],end="   ")
    if count % 7 == 0:
      print()
  print()


def ModifyMenu():
  print('-' * 22)
  print("# 修改姓名請輸入:   1 *")
  print("# 修改性別請輸入:   2 *")
  print("# 修改畢業年級請輸入: 3 *")
  print("# 修改公司資訊請輸入: 4 *")
  print("# 修改電話號碼請輸入: 5 *")
  print("# 修改家庭住址請輸入: 6 *")
  print("# 退出修改請輸入: 0 *")
  print('-' * 22)


def ModifyMsg():
  def ModifyName(pos):
    f = open('StudentMsg.txt','r+',encoding='utf-8')
    flist = f.readlines()
    name = input("輸入修改之後的姓名:")
    name += '\n'
    flist[pos + 1] = name
    f = open('StudentMsg.txt','w+',encoding='utf-8')
    f.writelines(flist)
    f.close()
    print("修改成功!")

  def ModifySex(pos):
    Sex = ['男','女']
    f = open('StudentMsg.txt',encoding='utf-8')
    flist = f.readlines()
    sex = input("輸入修改之後的性別:")
    if sex in Sex:
      sex += '\n'
      flist[pos + 2] = sex
      f = open('StudentMsg.txt',encoding='utf-8')
      f.writelines(flist)
      f.close()
      print("修改成功!")
    else:
      print("輸入錯誤!")
      print("修改失敗!")
      ModifySex(pos)

  def ModifyYear(pos):
    f = open('StudentMsg.txt',encoding='utf-8')
    flist = f.readlines()
    year = input("輸入修改之後的年級:")
    if int(year) > 2000:
      year += '\n'
      flist[pos + 3] = year
      f = open('StudentMsg.txt',encoding='utf-8')
      f.writelines(flist)
      f.close()
      print("修改成功!")
    else:
      print("輸入錯誤!")
      print("修改失敗!")
      ModifyYear(pos)

  def Modifycompany(pos):
    f = open('StudentMsg.txt',encoding='utf-8')
    flist = f.readlines()
    company = input("輸入修改之後的公司:")
    company += '\n'
    flist[pos + 4] = company
    f = open('StudentMsg.txt',encoding='utf-8')
    f.writelines(flist)
    f.close()
    print("修改成功!")

  def ModifyTell(pos):
    f = open('StudentMsg.txt',encoding='utf-8')
    flist = f.readlines()
    tell = input("輸入修改之後的電話號碼:")
    if len(tell) == 11:
      tell += '\n'
      flist[pos + 5] = tell
      f = open('StudentMsg.txt',encoding='utf-8')
      f.writelines(flist)
      f.close()
      print("修改成功!")
    else:
      print("輸入錯誤!")
      print("修改失敗!")
      ModifyTell(pos)

  def ModifyAddress(pos):
    f = open('StudentMsg.txt',encoding='utf-8')
    flist = f.readlines()
    address = input("輸入修改之後的地址:")
    address += '\n'
    flist[pos + 6] = address
    f = open('StudentMsg.txt',encoding='utf-8')
    f.writelines(flist)
    f.close()
    print("修改成功!")

  PrintAllMsg()
  id = input("請輸入你要修改的學號:")
  if id in IsIdRight():
    l2 = GetList()
    pos = l2.index(id)
    while 1:
      ModifyMenu()
      a = int(input("請輸入: "))
      while a:
        if a == 1:
          ModifyName(pos)
          break
        if a == 2:
          ModifySex(pos)
          break
        if a == 3:
          ModifyYear(pos)
          break
        if a == 4:
          Modifycompany(pos)
          break
        if a == 5:
          ModifyTell(pos)
          break
        if a == 6:
          ModifyAddress(pos)
          break
      if a == 0: # 按0退出程序
        break


def DelMsg():
  PrintAllMsg()
  id = input("請輸入你要刪除的學生的Id:")
  if id in IsIdRight():
    pos = GetList().index(id)
    f = open('StudentMsg.txt',encoding='utf-8')
    flist = f.readlines()
    for i in range(0,7):
      del flist[pos]
    f = open('StudentMsg.txt',encoding='utf-8')
    f.writelines(flist)
    f.close()
    print("刪除成功!")
    PrintAllMsg()
  else:
    print("學號輸入錯誤!")
    DelMsg()


def IsIdRight(): # 返回學號列表
  l1 = GetList()
  l2 = []
  i = 0
  while i < len(l1):
    l2.append(l1[i])
    i = i + 7
  return l2


def AddMsg(): # 新增資訊
  fiel = open('StudentMsg.txt','a',encoding='utf-8')

  def Inputid(): # 新增學號判斷
    id = (input("請輸入你的學號:"))
    l1 = IsIdRight()
    if not (int(id) > 1000 and (id in l1)):
      fiel.write('\n')
      fiel.writelines(id)
    else:
      if int(id) < 1000:
        print("學號輸入錯誤!")
        Inputid()
      if id in IsIdRight():
        print("學號存在!")
        Inputid()

  def Inputname(): # 新增姓名判斷
    name = input("請輸入你的姓名:")
    fiel.write('\n')
    fiel.writelines(name)

  def InputSex(): # 新增性別判斷
    sex = ['男','女']
    s1 = input("請輸入你的性別")
    if s1 in sex:
      fiel.write('\n')
      fiel.writelines(s1)
    else:
      print("性別輸入錯誤!")
      InputSex()

  def InputGaduYear(): # 新增畢業年級判斷
    year = (input("請輸入你的畢業年級:"))
    if int(year) > 2000:
      fiel.write('\n')
      fiel.writelines(year)
    else:
      print("畢業年級輸入錯誤!")
      InputGaduYear()

  def InputCompany(): # 新增公司資訊
    company = input("請輸入你的就業公司:")
    fiel.write('\n')
    fiel.writelines(company)

  def InputTell(): # 新增電話判斷
    tell = (input("請輸入你的電話號碼:"))
    if len(tell) == 11:
      fiel.write('\n')
      fiel.writelines(tell)
    else:
      print("電話號碼輸入錯誤!")
      InputTell()

  def InputAddress(): # 新增地址資訊
    add = input("請輸入你的家庭地址:")
    fiel.write('\n')
    fiel.writelines(add)

  Inputid()
  Inputname()
  InputSex()
  InputGaduYear()
  InputCompany()
  InputTell()
  InputAddress()
  fiel.close() # 關閉檔案


def Menu(): # 選單主介面
  print('-' * 22)
  print("# 檢視畢業生列表輸入: 1 *")
  print("# 新增畢業生資訊輸入: 2 *")
  print("# 修改畢業生資訊輸入: 3 *")
  print("# 查詢畢業生資訊輸入:4 *")
  print("# 刪除畢業生資訊輸入: 5 *")
  print("# 退出系統請輸入   0 *")
  print('-' * 22)


def FindMenu():
  print('-' * 22)
  print("# 搜尋學號請輸入: 1 *")
  print("# 搜尋姓名請輸入: 2 *")
  print("# 退出搜所請輸入 0 *")
  print('-' * 22)


def FindStu():
  def FindMsgById():
    id = input("請輸入你需要查詢的學生的學號:")
    if id in IsIdRight():
      pos = GetList().index(id)
      flist = GetList()
      print(StudentInfo)
      for i in range(0,7):
        print(flist[pos + i],end="   ")
      print()
    else:
      print("學號輸入錯誤!")
      FindMsgById()

  def FindMsgByName():
    name = input("請輸入你需要查詢的學生的姓名:")
    if name in GetList():
      pos = GetList().index(name) - 1
      flist = GetList()
      print(StudentInfo)
      for i in range(0,end="   ")
      print()
    else:
      print("姓名輸入錯誤!")
      FindMsgByName()

  while 1:
    FindMenu()
    a = int(input("請輸入: "))
    while a:
      if a == 1:
        FindMsgById()
        break
      if a == 2:
        FindMsgByName()
        break
    if a == 0:
      break


def main():
  Menu()
  while 1:
    a = int(input("請輸入: "))
    while a:

      if a == 1:
        PrintAllMsg()
        Menu()
        break
      if a == 2:
        AddMsg()
        Menu()
        break
      if a == 3:
        ModifyMsg()
        Menu()
        break
      if a == 4:
        FindStu()
        Menu()
        break
      if a == 5:
        DelMsg()
        Menu()
        break
    if a == 0: # 按0退出程序
      exit()


main()

相應的簡要測試:

Python使用檔案操作實現一個XX資訊管理系統的示例

Python使用檔案操作實現一個XX資訊管理系統的示例

Python使用檔案操作實現一個XX資訊管理系統的示例

相應的檔案:注意 該文字檔案應和程式碼檔案在同一個目錄下

Python使用檔案操作實現一個XX資訊管理系統的示例

注意 : 這裡採用分行進行資料的儲存,為了方便資料的準確修改,不需要一整行的資料進行修改那麼麻煩,插入和修改也更為精確

到此這篇關於Python使用檔案操作實現一個XX資訊管理系統的示例的文章就介紹到這了,更多相關Python XX資訊管理系統內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!