python3 を使ってテキストfileの中の特定の1行だけを指定して消去することは可能でしょうか? できる限りパッケージなどを使わないでできる方法があれば教えていただきたいです。また、自分が書いたコードに改善点があればよければ教えてください。
python3
1def createfile(): 2 file_name = str(input('Enter the file name: ')) 3 try: 4 score_file = open(file_name + '.txt', 'w') 5 score_file.close() 6 except: 7 print('An error occured at creating.') 8 else: 9 print(file_name + '.txt is created') 10 11def searchfile(): 12 file_name = str(input('Enter the file name which you want to see.: ')) 13 try: 14 score_file = open(file_name, 'r') 15 name = score_file.readline() 16 while name != '': 17 score = score_file.readline() 18 name = name.rstrip('\n') 19 score = score.rstrip('\n') 20 print(name, score) 21 name = score_file.readline() 22 except: 23 print('An error occured at adding.') 24 25def addfile(): 26 try: 27 file_name = str(input('Enter the file name which you want to add to.: ')) 28 add = '1' 29 while add == '1': 30 name = str(input('Enter a student name: ')) 31 score = str(input('Enter his/her score: ')) 32 score_file = open(file_name, 'a') 33 score_file.write('Name:'+ name + '\n') 34 score_file.write('Score:' + score + '\n') 35 score_file.close() 36 add = input('If you want to continue adding new data, press 1: ') 37 except(): 38 print('An error occured at adding.') 39 40def main(): 41 kc = 'y' 42 while kc == 'y': 43 press = input('Press 1 to create a new course score file.\nPress 2 to search into an existing course score file.\nPress 3 to add more scores to an existing course score file.: ') 44 if press == '1': 45 createfile() 46 elif press == '2': 47 searchfile() 48 elif press == '3': 49 addfile() 50 51 kc = input('If you continue process press y: ') 52 print ('Good Bye!') 53 54main()
プログラムのソースコードはcodeタグで囲ってくださいな。
ありがとうございます。不慣れで申し訳ないです。
回答2件
あなたの回答
tips
プレビュー