每次向檔案添加內容時,我都想對檔案進行計數或添加數字。
我的檔案由
Account|Username|Password
每當用戶添加另一個帳戶時,我都希望像這樣。
# Account Username Password
1 Facebook Name Pass
我添加帳戶的代碼是這樣的
def add_account():
acc = input("Enter the name of your account.")
username = input(f"Enter the username of your {acc}")
password = input(f"Enter the password of your {acc}")
ask = input(f" Do you like to save {acc} credentials? Y|N")
if ask == "Y":
with open("myfile.txt", "a") as file:
file.write("" acc username password)
file.close()
add_accout()
def view_account():
file = open("myfile.txt", "r")
line = file.readline()
for line in file:
a, b, c, d = line.split("|")
d = d.strip()
print(formatStr(a), formatStr(b), formatStr(c), formatStr(d))
view_account()
def formatStr(str):
nochars = 15
return str (" "*(nochars - len(str))
如何計算附加的行?
uj5u.com熱心網友回復:
正如 jarmod 在評論中所建議的那樣,您可以使用全域計數變數對每個添加的帳戶進行編號:
counting = 0
def add_account():
global counting
acc = input("Enter the name of your account.")
username = input(f"Enter the username of your {acc}")
password = input(f"Enter the password of your {acc}")
ask = input(f" Do you like to save {acc} credentials? Y|N")
if ask == "Y":
counting = 1
with open("myfile.txt", "a") as file:
file.write("" acc username password str(counting))
file.close()
add_account()
uj5u.com熱心網友回復:
如果您需要能夠退出程式,稍后重新啟動它,并讓它發現存盤在您資料庫中的最后一個帳號,那么您可以按如下方式計算下一個免費帳號:
def next_account_number():
next_num = 1
with open("myfile.txt", "r") as f:
# Read lines discarding empty lines
lines = f.read().splitlines()
lines = list(filter(lambda x: x != "", lines))
if len(lines) > 1:
account = lines[-1].split()
try:
next_num = int(account[0]) 1
except ValueError:
pass
return next_num
print("Next account number:", next_account_number())
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/344628.html
上一篇:添加函式引數會產生變數陰影,而沒有引數會導致重新分配?
下一篇:如何輸出值而不將其放入作業表?
