Question

Guest = {}
with open('LogIn.txt') as f:
    credentials = [x.strip().split(':') for x in f.readlines()]
    for username,password in credentials:
        Guest[username] = password
def DelUser():
    DB = open('LogIn.txt',"r+")
    username = DB.read()
    delete = raw_input("Input username to delete: ")
    if delete in username:
        <insert code to remove line containing username:password combination>

So, I have a LogIn.txt file with the following username:password combinations:

chris:test
char:coal
yeah:men
test:test
harhar:lololol

I want to delete the username:password combination that I want to in the object "delete" But the problem is, if I use the

if delete in username:

argument, it'll have to consider the password as well. and example, what if I have two accounts with the same password? Or like the one above. What path can I take for this one? Or am I missing something here?

Était-ce utile?

La solution

According to your current DelUser function, you can read the file, remove the line that start with the user to delete, and write a new one:

def DelUser():

    # read the current files, and get one line per user/password
    with open('LogIn.txt',"r+") as fd:
        lines = fd.readlines()

    # ask the user which one he want to delete
    delete = raw_input("Input username to delete: ")

    # filter the lines without the line starting by the "user:"
    lines = [x for x in lines if not x.startswith('%s:' % delete)]

    # write the final file
    with open('LogIn.txt', 'w') as fd:
        fd.writelines(lines)

Autres conseils

Use

if delete in Guest:

to test if delete is a key in Guest. Since the keys of Guest represent usernames, if delete in Guest tests if delete is a username.


You could use the fileinput module to rewrite the file "inplace":

import fileinput
import sys

def DelUser(Guest):
    delete = raw_input("Input username to delete: ")
    for line in fileinput.input(['LogIn.txt'], inplace = True, backup = '.bak'):
        if delete not in Guest:
            sys.stdout.write(line)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top