简体   繁体   English

如何仅删除 csv 的一行并将更改保存在同一个 csv 中? [Python]

[英]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.我正在用 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.您的用户名放在一个名为“lockedaccounts.csv”的 csv 文件中。一旦用户输入他们的恢复密钥,帐户就会被解锁。 I need the username to be deleted from the lockedaccounts.csv once they enter their recovery key.一旦他们输入恢复密钥,我需要从lockedaccounts.csv 中删除用户名。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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