计数本:number.txt
1 2 3 4
主程序:计数器
1 # Author: Stephen Yuan 2 # 递加计算器 3 import os 4 5 # 递加计算器 6 def calc(): 7 file_size = os.path.getsize('number.txt') 8 count = 1 9 if file_size == 0: 10 while True: 11 with open('number.txt', 'a', encoding='utf-8') as f: 12 f.write(str(count) + '\n') 13 print(count) 14 count += 1 15 if_choice() 16 elif file_size != 0: 17 while True: 18 with open('number.txt', 'r+', encoding='utf-8') as f: 19 lines = f.readlines() 20 last_line = int(lines[-1]) # 获取文件的最后一行内容 21 print(last_line) 22 last_line += 1 23 f.write(str(last_line) + '\n') 24 if_choice() 25 26 def if_choice(): 27 info = input('请选择:') 28 if info == 'a': 29 calc() 30 31 elif info == 'r': 32 with open('number.txt.', 'w', encoding='utf-8') as f: 33 pass 34 calc() 35 elif info == 'q': 36 exit() 37 38 def choice(): 39 choice = ''' 40 1.计数,请按‘a’ 41 2.重置,请按‘r’ 42 3.退出,请按‘q’ 43 '''.strip() 44 print(choice) 45 info = input('\n请选择:') 46 if info == 'a': 47 calc() 48 elif info == 'r': 49 with open('number.txt.', 'w', encoding='utf-8') as f: 50 pass 51 calc() 52 else: 53 exit() 54 55 choice()