0

I am currently creating an account management program where account details are stored in a .csv file, the user will enter the username of the account they want to delete but when I go delete a line it doesn't work correctly, if I use the "r+" mode it wont actually do anything and when I use "w" mode it will delete the entire file when i try to remove a single line.

Here is the code below for the delete function:

delUserName = input("enter the username of the account you want to delete")

with open(filename, 'r+') as csvFile:
    reader = csv.reader(csvFile, delimiter=",")
    writer = csv.writer(csvFile, delimiter=",")
    for rows in reader:
        if rows[1] == delUserName:
            writer.writerow("")

The csv file is setup as 1,username,password so rows[0] would be index, rows[1] would be username and rows[2] would be password

Any help will be much appreciated.

3
  • You don't write anything if the user name is not the one you want to delete Commented Mar 15, 2019 at 11:07
  • That is correct, but if the username is in the csv i want to delete that specific row, if the username isnt in the csv file i will print that out to the console and tell the user to type in another username or cancel the operation Commented Mar 15, 2019 at 11:12
  • 1
    I hadn't noticed that you were trying to read and write the same file at the same time. Don't do that, create a new file. Or use some db. Commented Mar 15, 2019 at 11:19

4 Answers 4

1

It is a bad idea to both iterate over lines of a file and write to it simultaneously. Use a second file to get all rows from the first file except those to be deleted, close both file handles, and finally move the new file in place of the old file. Or do all changes in memory, and then write them to the first file.

This question is mostly a duplicate of the following:

How to filter out specific data from a CSV via Python?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much for your input, ill implement the change now
1

Its easier if you use pandas dataframe: csvfile:testGen.csv # just for sample

    username    password
  0     user1   123
  1     user2   223
  2     user3   344
  3     user4   122

this is the sample data that csv file contains and this is how remove the row you want

import pandas as pd
df=pd.read_csv("testGen.csv")
df = df[~df["username"].str.contains("user2", na=False)]

then your answer will be:
username    password
0   user1   123
2   user3   344
3   user4   122

If you want to dump it csv file directly just write:

df = df[~df["username"].str.contains("user2", na=False)].to_csv('testGen1.csv', index = False)

Comments

0

Check if the value exist in the rows, if it exist then drop the row containing that value using index and rewrite the dataframe.

import pandas as pd
df = pd.read_csv('testFile.csv',index_col='index')
df.head()

if df[df['username'].isin(['satyam'])].shape[0]:
    df = df.drop(df[df.username == 'satyam'].index[-1]).reset_index(drop=True).rename_axis('index')
    print(df)

#to write into csv
df.to_csv('abc.csv')
#reading the new csv with dropped row
pd.read_csv('abc.csv')

Comments

0

It is easier to store name and password on the same line:

File 'accounts.csv':

User1,Password1
User2,Password2
User3,Password3

Then you can simply remove whole line:

acc = input('Enter the username of the account you want to delete: ')
with open('accounts.csv', 'r') as f:
    accounts = f.readlines()
acc_found = [x for x in accounts if x.split(',')[0].lower() == acc.lower()]
if acc_found:
    print('Remove you account: {}'.format(acc))
    accounts.remove(acc_found[0])
    with open('accounts.csv', 'w') as f:
        f.write(''.join(accounts))
else:
    print('Sorry! Account "{}" not found.'.format(acc))

Test 1:

Enter the username of the account you want to delete: User1
Remove you account: User1

Test 2:

Enter the username of the account you want to delete: User5
Sorry! Account "User5" not found.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.