简体   繁体   中英

How to delete only one row of a csv and save the changes in the same csv? [Python]

I'm making a login script in Python. in this script, if you input the wrong password too many times, your account becomes locked. Your username is put in a csv file called 'lockedaccounts.csv' Once the user enters their recovery key, the account is unlocked. I need the username to be deleted from the lockedaccounts.csv once they enter their recovery key.

Here is my current code

                   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

Thank you for your time.

The simplest code would be something like this:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM