Python-遞加計數器


計數本: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()

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM