1. <ul id="0c1fb"></ul>

      <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
      <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区

      RELATEED CONSULTING
      相關咨詢
      選擇下列產品馬上在線溝通
      服務時間:8:30-17:00
      你可能遇到了下面的問題
      關閉右側工具欄

      新聞中心

      這里有您想知道的互聯網營銷解決方案
      python學習之文件操作及異常處理

      在python,使用open函數,可以打開一個已經存在的文件,或者創(chuàng)建一個新文件。
      open(文件名,訪問模式) e.g. f = open('test.txt', 'w')
      如果文件不存在那么創(chuàng)建,如果存在那么就先清空,然后寫入數據
      python學習之文件操作及異常處理
      要讀取二進制文件,比如圖片、視頻等等,用'rb', 'wb', 'ab'等模式打開文件即可
      python學習之文件操作及異常處理
      python學習之文件操作及異常處理

      創(chuàng)新互聯專注于富順網站建設服務及定制,我們擁有豐富的企業(yè)做網站經驗。 熱誠為您提供富順營銷型網站建設,富順網站制作、富順網頁設計、富順網站官網定制、小程序定制開發(fā)服務,打造富順網絡公司原創(chuàng)品牌,更為您提供富順網站排名全網營銷落地服務。

      seek(offset, from)有2個參數: offset:偏移量 from:方向
      0:表示文件開頭;
      1:表示當前位置;
      2:表示文件末尾
      1). 把位置設置為:從文件開頭,偏移5個字節(jié)
      2). 把位置設置為:文件最開始
      3). 把位置設置為:文件最末尾

      01_open函數讀取文件操作.py

      #打開文件/etc/passwd, 默認的打開模式是'r'
      f = open('/etc/passwd')
      print(f.read())
      #io.UnsupportedOperation: not writable
      #f.write('hello')

      02_open以寫的方式打開文件.py

      """
      ##mode=r, 文件不存在,直接報錯; 只能read
      ##FileNotFoundError: [Errno 2] No such file or directory: 'doc/hello.txt'
      #f = open('doc/hello.txt')
      #print(f.read())

      ##mode=w, 1). 文件不存在,會自動創(chuàng)建文件; 2). 只能write 3). 自動清空文件內容
      #f = open('doc/hello.txt', mode='w')
      ##print("讀取文件中...", f.read())
      ##f.write('hello python\n')
      ##print("寫入成功......")

      """
      mode=a+,
      1). 文件不存在,會自動創(chuàng)建文件;
      2). r w
      3). 文件追加并不會清空文件
      """

      f = open('doc/world.txt', 'a+')
      #移動指針到文件最開始
      f.seek(0, 0)
      print(f.read())
      #f.write('hello python\n')

      print(f.closed)
      print(f.mode)
      print(f.name)

      f.close()
      print("關閉文件后.....")
      print(f.closed)
      print(f.mode)
      print(f.name)

      03_cp命令的實現.py

      import os
      os.path.exists('/etc/passwd')
      Out[3]: True
      os.path.exists('/etc/passwd1')
      Out[4]: False
      """
      import os
      src_filename = input("要拷貝的文件: ")
      #1). 判斷文件是否存在
      if os.path.exists(src_filename):
      dst_filename = input("目標文件: ")
      #2). mode='r'打開文件讀取文件內容
      #注意: 要讀取二進制文件,比如圖片、視頻等等,用'rb', 'wb', 'ab'等模式打開文件即可.
      src_f = open(src_filename, 'rb')
      content = src_f.read()

      #3). mode='r'打開文件寫入要拷貝的文件內容
      dst_f = open(dst_filename, 'wb')
      dst_f.write(content)
      
      #4). 關閉文件對象
      src_f.close()
      dst_f.close()
      
      print('拷貝成功')

      else:
      print("要拷貝的文件%s不存在" %(src_filename))

      04_文件讀寫操作.py

      from collections.abc import Iterable

      f = open('/etc/passwd', 'r')
      #當文件比較小時, 使用read、readlines方法讀取.
      print(f.read())
      print(''50)
      #當文件比較大時, 使用readline方法讀取.
      #將指針移動到文件最開始, 然后指針向右移動5個字節(jié)。
      f.seek(5, 0)
      print(f.readline())
      print(f.readline())
      print(''50)
      #將指針移動到文件最開始,
      f.seek(0, 0)
      print(f.readlines())

      #名詞: 可迭代對象: 可以通過for循環(huán)遍歷的對象
      #print("文件對象時可迭代對象嗎? ", isinstance(f, Iterable))
      for index, line in enumerate(f):
      print("第%s行" %(index+1), line)

      """
      from collections.abc import Iterable

      #需求: 將/etc/passwd文件后5行寫入doc/world.txt文件
      f1 = open('/etc/passwd')
      tail_five_line = f1.readlines()[-5:]
      #print(tail_five_line)
      #print(len(tail_five_line))
      f2 = open('doc/world.txt', 'w')
      f2.writelines(tail_five_line)
      print("write ok")

      """
      總結:方法一: 調用close()方法關閉文件。文件使用完畢后必須關閉,因為文件對象會占用操作系統的資源,
      并且操作系統同一時間能打開的文件數量也是有限的:
      方法二: Python引入了with語句來自動幫我們調用close()方法:
      python學習之文件操作及異常處理

      05_with語句工作原理.py

      with語句工作原理:
      python中的with語句使用于對資源進行訪問的場合,
      保證不管處理過程中是否發(fā)生錯誤或者異常都會自動
      執(zhí)行規(guī)定的(“清理”)操作,釋放被訪問的資源,
      比如有文件讀寫后自動關閉、線程中鎖的自動獲取和釋放等。

      """
      #enter, exit
      #f = open('xxxx')
      with open('/etc/passwd') as f:
      print('in with:', f.closed) # False
      print(f.readlines()[-1])
      print('out with:', f.closed) # True"""

      os,語義為操作系統,處理操作系統相關的功能,可跨平臺。 比如顯示當前目錄下所
      有文件/刪除某個文件/獲取文件大小......
      ? os模塊中的rename()可以完成對文件的重命名操作。
      rename(需要修改的文件名, 新的文件名)
      ? os模塊中的remove()可以完成對文件的刪除操作
      remove(待刪除的文件名)

      06_os模塊系統信息獲取.py

      import os

      #1). 返回操作系統類型, 值為posix,是Linux操作系統, 值為nt, 是windows操作系統
      print(os.name)
      os_name = 'Linux' if os.name =='posix' else 'Windows'
      print("當前操作系統: %s" %(os_name))

      #2). 操作系統的詳細信息
      detail_info = os.uname()
      print(detail_info)
      print("主機名:", detail_info.nodename)
      print("硬件架構:", detail_info.machine)
      print("系統名稱:", detail_info.sysname)
      print("Linux內核的版本號:", detail_info.release)

      #3). 系統環(huán)境變量等價于Linux的env命令
      print(os.environ)

      #4). 通過key值獲取環(huán)境變量對應的value值
      print(os.environ['PATH'])
      """

      07_os模塊文件和目錄的操作.py

      import os
      from os.path import isabs, abspath, join

      #1. 判斷是否為絕對路徑---'/tmp/hello', 'hello.png', 'qq/hello.mp3'
      print(isabs('/tmp/hello'))
      print(isabs('hello.py'))

      #2. 生成絕對路徑
      #filename = 'hello.py'
      filename = '/tmp/hello.py'
      if not isabs(filename):
      print(abspath(filename))

      #3. 'hello.png'
      #返回一個絕對路徑: 當前目錄的絕對路徑+ 文件名/目錄名

      #'/tmp/hello' , 'python.txt' ==== /tmp/hello/python.txt
      #C:\tmp\hello\python.txt
      print(join('/tmp/hello', 'python.txt'))

      #4.獲取目錄名或者文件名

      #5. 創(chuàng)建目錄/刪除目錄

      #6. 創(chuàng)建文件/刪除文件

      #7. 文件重命名(mv)

      #8. 判斷文件或者目錄是否存在

      #9. 分離后綴名和文件名

      #10. 將目錄名和文件名分離"""

      07_目錄常見應用.py

      """
      import os
      BASE_DIR = os.path.abspath(os.path.dirname(file))

      print(file) # /home/kiosk/201911python/day07_code/07_目錄常見應用.py
      print(os.path.dirname(file))
      print(os.path.abspath(os.path.dirname(file)))"""

      08_驗證碼生成器.py

      def draw_code_image(str_code='A34G'):
      #引入繪圖模塊, Image表示畫布對象; ImageDraw表示畫筆對象; ImageFont表示字體對象;
      from PIL import Image, ImageDraw, ImageFont
      #定義變量,用于畫面的背景色、寬、高
      #RGB:(255,0,0), (0, 255,0), (0, 0, 255)
      bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 255)
      width = 100
      height = 25
      #創(chuàng)建畫布對象
      im = Image.new('RGB', (width, height), bgcolor)
      #創(chuàng)建畫筆對象
      draw = ImageDraw.Draw(im)
      #調用畫筆的point()函數繪制噪點
      for i in range(100):
      xy = (random.randrange(0, width), random.randrange(0, height))
      fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
      draw.point(xy, fill=fill)
      #構造字體對象
      font = ImageFont.truetype('/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc',
      23)
      #構造字體顏色
      fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
      for index, item in enumerate(str_code):
      #print(5 +index20)) # (5,2) (25, 2), (45,2)
      draw.text((5 + (index
      20), 2), item, font=font, fill=fontcolor)
      return im

      """

      import random

      def generate_str_code(length=4):
      """隨機生成驗證碼"""
      import string
      strings = string.ascii_letters + string.digits
      return "".join(random.sample(strings, length))

      def draw_code_image(str_code):
      """根據給丁的字符串驗證碼繪制驗證碼圖片"""
      #引入繪圖模塊, Image表示畫布對象; ImageDraw表示畫筆對象; ImageFont表示字體對象;
      from PIL import Image, ImageDraw, ImageFont
      #定義變量,用于畫面的背景色、寬、高
      #RGB:(255,0,0), (0, 255,0), (0, 0, 255)
      width = 100
      height = 25
      white_color = (255, 255, 255)
      black_color = (0, 0, 0, 0)
      green_color = (0, 255, 0)
      #創(chuàng)建畫布對象
      im = Image.new('RGB', (width, height), white_color)
      #創(chuàng)建畫筆對象
      draw = ImageDraw.Draw(im)
      #調用畫筆的point()函數繪制噪點
      for i in range(100):
      xy = (random.randrange(0, width), random.randrange(0, height))
      draw.point(xy, fill=green_color)
      #構造字體對象 shell命令: fc-list :lang=zh
      font = ImageFont.truetype('doc/wqy-zenhei.ttc', 23)
      for index, item in enumerate(str_code):
      #print(5 +index20)) # (5,2) (25, 2), (45,2)
      draw.text((5 + (index
      20), 2), item, font=font, fill=black_color)
      return im

      if name== 'main':
      str_code = generate_str_code()
      #返回的圖片對象
      im = draw_code_image(str_code)
      im.save('hello.png')"""

      08_驗證碼生成器.py

      Author: lvah
      Date: 2019-12-15
      Connect: 976131979@qq.com
      Description:

      項目需求: 批量驗證碼圖片生成器
      1). 可生成數字、大寫、小寫字母及三者混合類型的驗證碼
      2). 支持自定義驗證碼字符數量
      3). 支持自動調整驗證碼圖片的大小
      4). 支持自定義干擾點的數量
      5). 支持自定義驗證碼圖文顏色
      """
      import os
      import random

      white_color = (255, 255, 255)
      black_color = (0, 0, 0, 0)
      green_color = (0, 255, 0)

      def generate_str_code(length=4):
      """隨機生成驗證碼"""
      import string
      strings = string.ascii_letters + string.digits
      return "".join(random.sample(strings, length))

      def draw_code_image(str_code, item_width=25, height=25, point_count=100,
      bg_color=black_color, font_color=white_color):
      """
      根據給定的字符串驗證碼繪制驗證碼圖片
      :param str_code:
      :param item_width:
      :param height:
      :param point_count:
      :param bg_color:
      :param font_color:
      :return:
      """
      #引入繪圖模塊, Image表示畫布對象; ImageDraw表示畫筆對象; ImageFont表示字體對象;
      from PIL import Image, ImageDraw, ImageFont
      #定義變量,用于畫面的背景色、寬、高
      #RGB:(255,0,0), (0, 255,0), (0, 0, 255)
      #根據驗證碼的長度自動調整畫布的寬度
      width = len(str_code) item_width
      #創(chuàng)建畫布對象
      im = Image.new('RGB', (width, height), bg_color)
      #創(chuàng)建畫筆對象
      draw = ImageDraw.Draw(im)
      #調用畫筆的point()函數繪制噪點
      for i in range(point_count):
      xy = (random.randrange(0, width), random.randrange(0, height))
      draw.point(xy, fill=green_color)
      #構造字體對象 shell命令: fc-list :lang=zh
      font = ImageFont.truetype('doc/wqy-zenhei.ttc', 23)
      for index, item in enumerate(str_code):
      #print(5 +index
      25)) # (5,2) (25, 2), (45,2)
      draw.text((5 + (index * 25), 0), item, font=font, fill=font_color)
      return im

      if name== 'main':
      from tqdm import tqdm
      verifyCodeCount = 100
      dirname = 'vCode'
      for count in tqdm(range(verifyCodeCount)):
      #He3x ===== He3x.png
      str_code = generate_str_code(length=10)
      #返回的圖片對象
      im = draw_code_image(str_code)
      #生成圖片文件的絕對路徑
      filename = os.path.join(dirname, str_code + random.choice(['.png', '.jpg']))
      im.save(filename)

      print("生成圖片驗證碼成功")

      """
      json模塊詳解:
      python學習之文件操作及異常處理 python學習之文件操作及異常處理
      python 中str類型到JSON中轉為unicode類型,None轉為null,dict對應object;
      pyhton中的集合不能轉成json格式
      ? ensure_ascii=False: 中文存儲需要設定
      ? indent=4: 增加縮進,增強可讀性,但縮進空格會使數據變大
      ? separators=(',',':'): 自定義分隔符,元素間分隔符為逗號, 字典key和value值的分隔符為冒號
      ? sort_keys=True: 字典排序

      10_存儲json數據.py

      """
      import json
      info = dict(user1='00000', user2='11111', 粉條='1111')

      #編碼: 字典轉成json數據格式
      json_info = json.dumps(info)
      print(info, json_info)
      print(type(info), type(json_info))

      #編碼: 字典轉成json并存儲未文件
      json.dump(info, open('doc/info.json', 'w'), indent=4, ensure_ascii=False)
      print("寫入json文件成功")

      """

      11_加載json文件.py

      """

      import json

      filename = 'doc/info.json'
      #解碼: 將文件中的json數據轉換成python對象及型處理
      python_info = json.load(open(filename))
      print(python_info)
      print(python_info.get('粉條'))

      """
      我們碰到集合對象, datetime對象,或者自定義的類對象等json默認不支持的數據類型時,我們就需
      要自定義編解碼函數。有兩種方法來實現自定義編解碼。

      12_json模塊自定義編碼與解碼.py

      """

      from datetime import datetime
      from datetime import date
      import json

      def time2str(dateObj):
      return str(dateObj)

      dt = datetime.now()
      today = date.today()

      #自定義編碼和解碼
      with open('doc/date.json', 'w') as f:
      #Object of type date is not JSON serializable
      json.dump(today, f, default=time2str)
      print('dump ok')"""

      python的pickle模塊實現了python的所有數據序列和反序列化。與JSON不同的是pickle不是用于多種
      語言間的數據傳輸,它僅作為python對象的持久化或者python程序間進行互相傳輸對象的方法,因此
      它支持了python所有的數據類型。cPickle是pickle模塊的C語言編譯版本相對速度更快。
      總結:
      1、JSON只能處理基本數據類型。pickle能處理所有Python的數據類型。
      2、JSON用于各種語言之間的字符轉換。pickle用于Python程序對象的持久化或者Python程序間對象
      網絡傳輸,但不同版本的Python序列化可能還有差異。

      13_pickle數據的序列化.py

      import pickle

      #編碼
      from datetime import date
      today = date.today()
      with open('date.pkl', 'wb') as f:
      pickle.dump(today, f)
      print('pickle dump ok')

      #解碼: 反序列化
      with open('date.pkl', 'rb') as f:
      today = pickle.load(f)
      print('pickle load ok')
      print(today)

      """

      15_忽略注釋行.py

      """

      filename = 'doc/passwd.bak'
      with open(filename) as f:
      for line in f:
      if not line.startswith('#'):
      print(line)"""
      異常處理機制
      Python 的異常機制主要依賴 try 、except 、else、finally 和 raise 五個關鍵字。
      ? try 關鍵字后縮進的代碼塊簡稱 try 塊,它里面放置的是可能引發(fā)異常的代碼;
      ? except 關鍵字對應異常類型和處理該異常的代碼塊;
      ? 多個 except 塊之后可以放一個 else 塊,表明程序不出現異常時還要執(zhí)行 else 塊;
      ? finally 塊用于回收在 try 塊里打開的物理資源,異常機制會保證 finally 塊總被執(zhí)行;
      ? raise 用于引發(fā)一個實際的異常,raise 可以單獨作為語句使用,引發(fā)一個具體的異常對象;
      除了處理實際的錯誤條件之外,對于異常還有許多其它的用處。在標準 Python 庫中
      一個普通的用法就是試著導入一個模塊,然后檢查是否它能使用。導入一個并不存在的
      模塊將引發(fā)一個 ImportError 異常。
      你可以使用這種方法來定義多級別的功能――依靠在運行時哪個模塊是有效的,或支
      觸發(fā)異常
      持多種平臺 (即平臺特定代碼被分離到不同的模塊中)。
      Python 允許程序自行引發(fā)異常,自行引發(fā)異常使用 raise 語句來完成。
      raise語句中 Exception 是異常的類型(例如,NameError)參數標準異常中任一種,
      args 是自已提供的異常參數。
      raise [Exception [, args [, traceback]]]
      自定義異常
      用戶自定義異常都應該繼承 Exception 基類或 Exception 的子類,在自定義異常類時基
      本不需要書寫更多的代碼,只要指定自定義異常類的父類即可
      ? 不要過度使用異常
      ? 不要使用過于龐大的 try 塊
      ? 不要忽略捕獲到的異常

      16_異常處理機制.py

      import os
      dirname = 'dir'
      filename = os.path.join(dirname, 'hello.html') # dir/hello.html

      #try 關鍵字后縮進的代碼塊簡稱 try 塊,它里面放置的是可能引發(fā)異常的代碼;
      try:
      with open(filename, 'w') as f:
      f.write('hello')
      #except 關鍵字對應異常類型和處理該異常的代碼塊;
      except FileNotFoundError as e:
      os.mkdir(dirname)
      #如何沒有產生任何異常時, 執(zhí)行的內容
      else:
      print('no exception')
      #finally 塊用于回收在 try 塊里打開的物理資源,異常機制會保證 finally 塊總被執(zhí)行
      finally:
      print("不管是否有異常都要執(zhí)行的代碼")
      """

      17_異常處理范例.py

      """

      try:
      print(10/0) # ZeroDivisionError, 異常處理之后, try里面的代碼并不會繼續(xù)執(zhí)行。
      print(a) # NameError
      except ZeroDivisionError as e:
      print('zero')
      except NameError as e:
      print('name')
      else:
      print('ok')

      print('step 1')"""

      18_拋出異常.py

      #IndexError
      #NameError

      class AgeError(ValueError):
      pass

      age = 1000
      if 0 < age < 150:
      print('age legal')
      else:
      raise AgeError('age error')

      作業(yè):

      1 批量改名:

      import os
      path = 'doc/'
      for i in os.listdir(path):
          new_name = '[西部開源]-' + i
          os.rename(os.path.join(path,i),os.path.join(path,new_name))
          print(new_name)
      2 忽略注釋行:
      filename = 'doc/passwd.bak'
      with open(filename) as f:
          for line in f:
              if not line.startswith("#"):
                  print(line)
      3 密碼簿:
      import  os
      f = open('doc/book.txt','a+')
      def main():
          print("密碼簿管理系統")
          print("1.增加網址和密碼")
          print("2.刪除網址和密碼")
          print("3.修改網址和密碼")
          print("4.查詢網址和密碼")
          print("5.退出系統")
      def add_book():
          f = open("doc/book.txt",'a+')
          web = input("輸入網址:")
          passwd = input("輸入密碼:")
          f.write("網址名:"+web+"\t"+"密碼:"+passwd+"\n")
          print("寫入成功")
          f.close()
      def  del_book():
          f = open("doc/book.txt", 'a+')
          web = input("輸入要刪除的網址:")
          f.seek(0,0)      # 重新設置位置到文件開頭
          a = f.readlines()
          temp_file = open("doc/tmp.txt",'w')
          i = 0
          for temp in a:
              b = temp.split("\t")
              net_name = b[0].split(":")
              if web == net_name[1]:
                  print("刪除成功!")
                  i = 1
                  continue
              else:
                  temp_file.write(temp)
          if i == 0:
              print("沒有找到要刪除的網址!!")
          temp_file.close()
          f.close()
          os.remove("doc/book.txt")
          os.rename("doc/tmp.txt", "doc/book.txt")
      def  change_book():
          f = open("doc/book.txt", "a+")
          f.seek(0, 0)       # 重新設置位置到文件開頭
          re_net = input("請輸入要修改的網址名:")
          a = f.readlines()
          temp_file = open("doc/tmp.txt", "w+")
          i = 0
          for temp in a:
              b = temp.split("\t")
              net_name = b[0].split(":")
              if re_net == net_name[1]:
                  print("要修改的網址已找到!!")
                  web = input("請輸入新的網址名")
                  passwd = input("請輸入新的密碼")
                  temp_file.write("網址名:" + web + "\t" + "密碼:" + passwd + "\n")
                  print("修改成功!!")
                  i = 1
                  continue
              else:
                  temp_file.write(temp)
          if i == 0:
              print("沒有找到要修改的網址!!")
      
          temp_file.close()
          f.close()
          os.remove("doc/book.txt")
          os.rename("doc/tmp.txt", "doc/book.txt")
      
      def find_book():
          f = open("doc/book.txt")
          f.seek(0, 0) # 重新設置位置到文件開頭
          goal = input("請輸入要查詢的網址名:")
          content = f.readlines()
          i = 0
          length = len(content)
          for temp in content:
              i += 1
              b = temp.split("\t")
              net_name = b[0].split(":")
              if goal == net_name[1]:
                  print(temp, end="")
                  i = 1
              elif i == length and goal != net_name:
                  print("沒有找到。。")
                  break
          f.close()
      main()
      while True:
          num = input("請輸入序號:\n")
          num = int(num)
          if num == 1:
              add_book()
          elif num == 2:
              del_book()
          elif num == 3:
              change_book()
          elif num == 4:
              find_book()
          elif num == 5:
              f.close()
              exit()
          else:
              print("請輸入正確序號")
              continue
      main()

      學生管理系統(文件版)

      import re  # 導入正則表達式模塊
      import os  # 導入操作系統模塊
      
      filename = "students.txt"  # 定義保存學生信息的文件名
      
      def menu():
          # 輸出菜單
          print('''
                          學生信息管理系統
      
              =============== 功能菜單 ===============        
      
          │   1 錄入學生信息                             │
          │   2 查找學生信息                             │
          │   3 刪除學生信息                             │
          │   4 修改學生信息                             │
          │   5 排序                                    │
          │   6 統計學生總人數                            │
          │   7 顯示所有學生信息                          │
          │   0 退出系統                                 
      
          ''')
      
      def main():
          ctrl = True  # 標記是否退出系統
          while (ctrl):
              menu()  # 顯示菜單
              option = input("請選擇:")  # 選擇菜單項
              option_str = re.sub("\D", "", option)  # 提取數字
              if option_str in ['0', '1', '2', '3', '4', '5', '6', '7']:
                  option_int = int(option_str)
                  if option_int == 0:  # 退出系統
                      print('您已退出學生成績管理系統!')
                      ctrl = False
                  elif option_int == 1:  # 錄入學生成績信息
                      insert()
                  elif option_int == 2:  # 查找學生成績信息
                      search()
                  elif option_int == 3:  # 刪除學生成績信息
                      delete()
                  elif option_int == 4:  # 修改學生成績信息
                      modify()
                  elif option_int == 5:  # 排序
                      sort()
                  elif option_int == 6:  # 統計學生總數
                      total()
                  elif option_int == 7:  # 顯示所有學生信息
                      show()
      
      '''1 錄入學生信息'''
      def insert():
          stdentList = []        # 保存學生信息的列表
          mark = True  # 是否繼續(xù)添加
          while mark:
              id = input("請輸入ID(如 1001):")
              if not id:  # ID為空,跳出循環(huán)
                  break
              name = input("請輸入名字:")
              if not name:  # 名字為空,跳出循環(huán)
                  break
              try:
                  english = int(input("請輸入英語成績:"))
                  python = int(input("請輸入Python成績:"))
                  c = int(input("請輸入C語言成績:"))
              except:
                  print("輸入無效,不是整型數值....重新錄入信息")
                  continue
              stdent = {"id": id, "name": name, "english": english, "python": python, "c": c}  # 將輸入的學生信息保存到字典
              stdentList.append(stdent)  # 將學生字典添加到列表中
              inputMark = input("是否繼續(xù)添加?(y/n):")
              if inputMark == "y":  # 繼續(xù)添加
                  mark = True
              else:  # 不繼續(xù)添加
                  mark = False
          save(stdentList)  # 將學生信息保存到文件
          print("學生信息錄入完畢!!!")
      
      #將學生信息保存到文件
      def save(student):
          try:
              students_txt = open(filename, "a")  # 以追加模式打開
          except Exception as e:
              students_txt = open(filename, "w")  # 文件不存在,創(chuàng)建文件并打開
          for info in student:
              students_txt.write(str(info) + "\n")  # 按行存儲,添加換行符
          students_txt.close()  # 關閉文件
      
      '''2 查找學生成績信息'''
      def search():
          mark = True
          student_query = []  # 保存查詢結果的學生列表
          while mark:
              id = ""
              name = ""
              if os.path.exists(filename):  # 判斷文件是否存在
                  mode = input("按ID查輸入1;按姓名查輸入2:")
                  if mode == "1":
                      id = input("請輸入學生ID:")
                  elif mode == "2":
                      name = input("請輸入學生姓名:")
                  else:
                      print("您的輸入有誤,請重新輸入!")
                      search()  # 重新查詢
                  with open(filename, 'r') as file:  # 打開文件
                      student = file.readlines()  # 讀取全部內容
                      for list in student:
                          d = dict(eval(list))  # 字符串轉字典
                          if id is not "":  # 判斷是否按ID查
                              if d['id'] == id:
                                  student_query.append(d)  # 將找到的學生信息保存到列表中
                          elif name is not "":  # 判斷是否按姓名查
                              if d['name'] == name:
                                  student_query.append(d)  # 將找到的學生信息保存到列表中
                      show_student(student_query)  # 顯示查詢結果
                      student_query.clear()  # 清空列表
                      inputMark = input("是否繼續(xù)查詢?(y/n):")
                      if inputMark == "y":
                          mark = True
                      else:
                          mark = False
              else:
                  print("暫未保存數據信息...")
                  return
      
      '''3 刪除學生成績信息'''
      
      def delete():
          mark = True  # 標記是否循環(huán)
          while mark:
              studentId = input("請輸入要刪除的學生ID:")
              if studentId is not "":  # 判斷要刪除的學生是否存在
                  if os.path.exists(filename):  # 判斷文件是否存在
                      with open(filename, 'r') as rfile:  # 打開文件
                          student_old = rfile.readlines()  # 讀取全部內容
                  else:
                      student_old = []
                  ifdel = False  # 標記是否刪除
                  if student_old:  # 如果存在學生信息
                      with open(filename, 'w') as wfile:  # 以寫方式打開文件
                          d = {}  # 定義空字典
                          for list in student_old:
                              d = dict(eval(list))  # 字符串轉字典
                              if d['id'] != studentId:
                                  wfile.write(str(d) + "\n")  # 將一條學生信息寫入文件
                              else:
                                  ifdel = True  # 標記已經刪除
                          if ifdel:
                              print("ID為 %s 的學生信息已經被刪除..." % studentId)
                          else:
                              print("沒有找到ID為 %s 的學生信息..." % studentId)
                  else:  # 不存在學生信息
                      print("無學生信息...")
                      break  # 退出循環(huán)
                  show()  # 顯示全部學生信息
                  inputMark = input("是否繼續(xù)刪除?(y/n):")
                  if inputMark == "y":
                      mark = True  # 繼續(xù)刪除
                  else:
                      mark = False  # 退出刪除學生信息功能
      
      '''4 修改學生成績信息'''
      
      def modify():
          show()  # 顯示全部學生信息
          if os.path.exists(filename):  # 判斷文件是否存在
              with open(filename, 'r') as rfile:  # 打開文件
                  student_old = rfile.readlines()  # 讀取全部內容
          else:
              return
          studentid = input("請輸入要修改的學生ID:")
          with open(filename, "w") as wfile:  # 以寫模式打開文件
              for student in student_old:
                  d = dict(eval(student))  # 字符串轉字典
                  if d["id"] == studentid:  # 是否為要修改的學生
                      print("找到了這名學生,可以修改他的信息!")
                      while True:  # 輸入要修改的信息
                          try:
                              d["name"] = input("請輸入姓名:")
                              d["english"] = int(input("請輸入英語成績:"))
                              d["python"] = int(input("請輸入Python成績:"))
                              d["c"] = int(input("請輸入C語言成績:"))
                          except:
                              print("您的輸入有誤,請重新輸入。")
                          else:
                              break  # 跳出循環(huán)
                      student = str(d)  # 將字典轉換為字符串
                      wfile.write(student + "\n")   # 將修改的信息寫入到文件
                      print("修改成功!")
                  else:
                      wfile.write(student)  # 將未修改的信息寫入到文件
          mark = input("是否繼續(xù)修改其他學生信息?(y/n):")
          if mark == "y":
              modify()  # 重新執(zhí)行修改操作
      
      '''5 排序'''
      
      def sort():
          show()  # 顯示全部學生信息
          if os.path.exists(filename):  # 判斷文件是否存在
              with open(filename, 'r') as file:  # 打開文件
                  student_old = file.readlines()  # 讀取全部內容
                  student_new = []
              for list in student_old:
                  d = dict(eval(list))  # 字符串轉字典
                  student_new.append(d)  # 將轉換后的字典添加到列表中
          else:
              return
          ascORdesc = input("請選擇(0升序;1降序):")
          if ascORdesc == "0":  # 按升序排序
              ascORdescBool = False           # 標記變量,為False表示升序排序
          elif ascORdesc == "1":  # 按降序排序
              ascORdescBool = True          # 標記變量,為True表示降序排序
          else:
              print("您的輸入有誤,請重新輸入!")
              sort()
          mode = input("請選擇排序方式(1按英語成績排序;2按Python成績排序;3按C語言成績排序;0按總成績排序):")
          if mode == "1":  # 按英語成績排序
              student_new.sort(key=lambda x: x["english"], reverse=ascORdescBool)
          elif mode == "2":  # 按Python成績排序
              student_new.sort(key=lambda x: x["python"], reverse=ascORdescBool)
          elif mode == "3":  # 按C語言成績排序
              student_new.sort(key=lambda x: x["c"], reverse=ascORdescBool)
          elif mode == "0":  # 按總成績排序
              student_new.sort(key=lambda x: x["english"] + x["python"] + x["c"], reverse=ascORdescBool)
          else:
              print("您的輸入有誤,請重新輸入!")
              sort()
          show_student(student_new)  # 顯示排序結果
      
      ''' 6 統計學生總數'''
      
      def total():
          if os.path.exists(filename):  # 判斷文件是否存在
              with open(filename, 'r') as rfile:  # 打開文件
                  student_old = rfile.readlines()  # 讀取全部內容
                  if student_old:
                      print("一共有 %d 名學生!" % len(student_old))
                  else:
                      print("還沒有錄入學生信息!")
          else:
              print("暫未保存數據信息...")
      
      ''' 7 顯示所有學生信息 '''
      
      def show():
          student_new = []
          if os.path.exists(filename):  # 判斷文件是否存在
              with open(filename, 'r') as rfile:  # 打開文件
                  student_old = rfile.readlines()  # 讀取全部內容
              for list in student_old:
                  student_new.append(eval(list))  # 將找到的學生信息保存到列表中
              if student_new:
                  show_student(student_new)
          else:
              print("暫未保存數據信息...")
      
      #將保存在列表中的學生信息顯示出來
      def show_student(studentList):
          from prettytable import PrettyTable
          if not studentList:
              print("(o@.@o) 無數據信息 (o@.@o) \n")
              return
          field_names = ("ID", "名字", "英語成績", "Python成績", "C語言成績", "總成績")
          table = PrettyTable(field_names=field_names)
          for info in studentList:
              sum_score = info.get('english', 0) + info.get('python', 0) + info.get('c', 0)
              row = list(info.values())
              row.append(sum_score)
              table.add_row(row)
          print(table)
      
      if __name__ == "__main__":

      新聞標題:python學習之文件操作及異常處理
      網站路徑:http://www.ef60e0e.cn/article/pieigh.html
      99热在线精品一区二区三区_国产伦精品一区二区三区女破破_亚洲一区二区三区无码_精品国产欧美日韩另类一区
      1. <ul id="0c1fb"></ul>

        <noscript id="0c1fb"><video id="0c1fb"></video></noscript>
        <noscript id="0c1fb"><listing id="0c1fb"><thead id="0c1fb"></thead></listing></noscript>

        德庆县| 绍兴市| 南安市| 沙洋县| 广汉市| 耒阳市| 抚顺县| 渑池县| 浏阳市| 图木舒克市| 淳安县| 铁岭县| 新乐市| 雷波县| 永胜县| 阜阳市| 崇明县| 霸州市| 昆明市| 衢州市| 耒阳市| 阿合奇县| 信宜市| 平陆县| 辉县市| 龙州县| 晴隆县| 灵丘县| 赫章县| 大方县| 万载县| 惠来县| 新田县| 恩平市| 大英县| 青铜峡市| 晋江市| 巴林左旗| 瑞丽市| 房产| 嘉祥县|