1. 程式人生 > >python3之對本地TXT文件進行增加,刪除,修改,查看功能。

python3之對本地TXT文件進行增加,刪除,修改,查看功能。

str line 進行 內容 測試 class alt nes inpu

由於是初學,代碼如有不足,歡迎指出!

本博客記錄我的編程之路,記錄所學到的知識,分享所學心得!

這是我的一個作業。

首先分析要求:

  1. 創建一個TXT文件用於存儲賬號與密碼
  2. 實現對文件進行增加,刪除,修改,查看的功能

分析思路:

  1. 先寫一個選擇的菜單
  2. 列出我們要寫的自定義函數
  3. 實現增加,刪除,修改,查看功能的主要方法是讀取文件返回一個列表,然後對列表進行增加,刪除,修改,查看最後又把列表寫入文件。

 1 def jia(LIST):          #1增加函數
 2     print(空格加回車退出!)
 3     while True:
 4         S = input(
輸入賬號:) 5 if (S== ): 6 break 7 S2=input(輸入密碼:) 8 LIST.append(S+ +S2+\n) 9 with open(wj-4.txt, w)as F: 10 F.writelines(LIST) 11 12 def cha(LIST): #2查看函數 13 print(文件內容為下:) 14 for i in LIST: 15 print
(i.strip(\n)) 16 input("按任意鍵返回菜單!") 17 cai(LIST) 18 19 def shan(LIST): #3刪除函數 20 print(輸入 -1 退出!) 21 while True: 22 R = int(input(請輸入刪除第幾個:)) 23 if (R==-1): 24 break 25 del LIST[R - 1] 26 with open(wj-4.txt, w)as F: 27
F.writelines(LIST) 28 29 def gai(LIST): #5修改函數 30 print(輸入 -1 退出!) 31 while True: 32 R = int(input(請輸入修改第幾個:)) 33 if (R==-1): 34 break 35 R2 = input(輸入修改後的字符:) 36 del LIST[R - 1] 37 LIST.insert(R - 1, R2) 38 print(LIST) 39 40 def du(): #讀取文件函數 41 with open(wj-4.txt, r)as f: 42 LIST = f.readlines() 43 return LIST 44 45 def cai(LIST): #菜單函數 46 while True: 47 print(菜單選擇:\n(1)增加功能\n(2)查看功能\n(3)刪除功能\n(4)修改功能\n(5)退出) 48 A=int(input(請輸入:)) 49 if (A==1): 50 jia(LIST) 51 elif (A==2): 52 cha(LIST) 53 elif (A==3): 54 shan(LIST) 55 elif (A==4): 56 gai(LIST) 57 elif (A==5): 58 print(退出成功!\n歡迎下次使用!) 59 break 60 else:print(請正確輸入選擇!) 61 62 if __name__==__main__: 63 try: 64 LIST = du() # 返回列表 65 cai(LIST) #菜單 66 except:print(出現未知錯誤!)

測試圖:

技術分享圖片

這個內容主要考核對列表與文件的熟悉。

python3之對本地TXT文件進行增加,刪除,修改,查看功能。