Q:

username and password python program using dictionaries and writing to a file how do I do it without repetition

Firstly, I am a beginner with python so please refrain from any advanced answers unless necessary. I'm writing a login program which requires a username and password, I am trying to do it so it reads a file adds that to a dictionary then people login or create new logins and writes the new logins (if any) into the file for it to then get read and written back into the dictionary when I re-run the program... The problem I am running into is that when a new login is created it writes the new login into the file but at the same time it writes the other login in the dictionary into the file again. Is there a way to make sure the username and pass doesn't get repeated? Here's an example of what the text file would look like:
joe  dw < ---- old login and pass
joe  dw <---- repeated login and pass
jack  dw <--- new login and pass

This is my code sorry if it looks confusing or if you're mad that I don't have many comments I'm just new to commenting everything I do:
login = {} 
def fileToDict():
    '''this reads the file and writes it into the dictionary'''
    with open("login.txt", "r") as f:
        for line in f:
            (key, val) = line.split()
            login[key] = val

def addUser(username, password):
    '''basic user and login function'''
    if username in login:
        print("Username already exists")
    else:
        login[username] = password
        dictToFile()
def checkUser(username, password):
    '''checks where the username and password is in the dictionary'''
    if username in login:
        if password == login[username]:
            return True
        else:
            return False
    else:
        return False
def dictToFile():
    '''this writes the current dictionary into a file'''
    with open("login.txt", "a+") as f:
        for k, v in login.items():
            line = '{}  {}'.format(k, v) 
            print(line, file=f)        
fileToDict()
addUser("john","dw")
print(login)

A:

In dictToFile, you opened the file for appending ("a+"), which adds to the end of the file.  If you want to to overwrite what is already there, use "w".

