[英]How to delete only one row of a csv and save the changes in the same csv? [Python]
我正在用 Python 制作一個登錄腳本。 在此腳本中,如果您多次輸入錯誤密碼,您的帳戶將被鎖定。 您的用戶名放在一個名為“lockedaccounts.csv”的 csv 文件中。一旦用戶輸入他們的恢復密鑰,帳戶就會被解鎖。 一旦他們輸入恢復密鑰,我需要從lockedaccounts.csv 中刪除用戶名。
這是我當前的代碼
for k in range(0, len(col0)):
if col0[k] == username_recovery and col1[k] == recoverykeyask:
messagebox.showinfo('Account Recovery Successful', "Your account has been recovered.")
break
else:
accountscanningdone = False
else:
accountrecovered = False
感謝您的時間。
最簡單的代碼是這樣的:
import csv
#when you want to add
with open('lockedaccounts.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["username2"])
#when you want to delete
rows = []
with open('lockedaccounts.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
rows.append(row)
rows.remove(['username2'])
with open('lockedaccounts.csv', 'w') as file:
writer = csv.writer(file)
writer.writerows(rows)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.