Since it is a beginner, if the code is insufficient, please point out!
This blog records my programming journey, records what I have learned, and shares what I have learned!
This is one of my homework.
First analyze the requirements:
- Create a TXT file to store account and password
- Realize the functions of adding, deleting, modifying and viewing files
analysis of idea:
- Write a menu of choices first
- List the custom functions we want to write
- The main method to realize the functions of adding, deleting, modifying and viewing is to read the file and return a list, then add, delete, modify the list, and finally write the list to the file.
1 def jia(LIST): # 1 Add function 2 print ( ' Space and carriage return to exit! ' ) 3 while True: 4 S = input( ' Enter account number: ' ) 5 if (S== ' ' ): 6 break 7 S2=input( ' Enter password: ' ) 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 view function 13 print ( ' The content of the file is below: ' ) 14 for i in LIST: 15 print (i.strip ( ' \n ' )) 16 input( " Press any key to return to the menu! " ) 17 cai(LIST) 18 19 def shan(LIST): # 3 delete function 20 print( ' Enter -1 to exit! ' ) 21 while True: 22 R = int(input( ' Please enter the delete number: ' )) 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 Modify the function 30 print ( ' Enter -1 to exit!' ) 31 while True: 32 R = int(input( ' Please enter the modified number: ' )) 33 if (R==-1 ): 34 break 35 R2 = input( ' Enter the modified character: ' ) 36 del LIST[R - 1 ] 37 LIST.insert(R - 1 , R2) 38 print (LIST) 39 40 def du(): #Read file function 41 with open( ' wj-4.txt ' , ' r' )as f: 42 LIST = f.readlines() 43 return LIST 44 45 def cai(LIST): #Menu function 46 while True: 47 print ( ' Menu selection:\n(1)Add function\n(2) View function\n(3)Delete function\n(4)Modify function\n(5)Exit ' ) 48 A=int(input( ' Please 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 ( ' Exit successfully!\nWelcome next time! ' ) 59 break 60 else : print ( ' Please enter the selection correctly! ' ) 61 62 if __name__ == ' __main__ ' : 63 try : 64 LIST = du() #return list 65cai (LIST) #Menu 66 except : print ( ' An unknown error occurred! ' )
Test chart:
This content mainly assesses familiarity with lists and files.