0

I'm making what is supposed to be just a very basic OS during my free time. However, I'm trying to make it so that you can have as many users as you want, but every time I make a new user, it deletes the old one. So far I have this:

def typer():
    print("Start typing to get started. Unfortunately, you cannot currently save your files.")
    typerCMD = input("  ")
    CMDLine()


def CMDLine():
    print("Hello, and welcome to your new operating system. Type 'help' to get started.")
    cmd = input("~$: ")
    if cmd == ("help"):
        print("Use the 'leave' command to shut down the system. Use the 'type' command to start a text editor.")
    cmdLvl2 = input("~$: ")
    if cmdLvl2 == ("leave"):
        quit()
    if cmdLvl2 == ("type"):
        typer()

def redirect():
    signIn()

def mUserRedirect():
    makeUser()

def PwordSignIn():
    rPword = input("Password: ")
    with open('passwords.txt', 'r') as f:
        for line in f:
            print(line)
            if rPword == (line):
                CMDLine()
            else:
                print("Incorrect password.")
                signIn()

def signIn():
    rUname = input("Username: ")
    with open('usernames.txt', 'r') as f:
        for line in f:
            print(line)
            if rUname == (line):
                PwordSignIn()
            else:
                print("Username not found.")
                mUserRedirect()

def makeUser():
    nUname = input("New username: ")
    nPword = input("Create a password for the user: ")

    with open('usernames.txt', 'w') as f:
        f.write(nUname)
    with open('passwords.txt', 'w') as f:
        f.write(nPword)
    signIn()

print("Create a new user? (Y/N) ")
nUser = input("")
if nUser == ("N"):
    signIn()
if nUser == ("n"):
    signIn()
if nUser == ("Y"):
    makeUser()
if nUser == ("y"):
    makeUser()

So how can I write to the file without getting rid of everything that was already in there?

J. Bridges
  • 149
  • 1
  • 7
  • 1
    `w` - open file for writing, place cursor at start of file (e.g. overwrite). you want `w+` - open file for writing, place cursor at END of file (e.g. append). – Marc B Feb 18 '16 at 19:50
  • 4
    When opening, use mode 'a' for append rather than 'w' for write. – Dan Feb 18 '16 at 19:50
  • You can use `a` mode for append to a file , `w` mode writes from start of file – ᴀʀᴍᴀɴ Feb 18 '16 at 19:51

1 Answers1

1

It depends on the "mode" you're using when opening your file. From the documentation:

  • 'r' open for reading (default)
  • 'w' open for writing, truncating the file first
  • 'a' open for writing, appending to the end of the file if it exists

So all you have to do now is:

with open('usernames.txt', 'a') as f:
    f.write(nUname)
julienc
  • 19,087
  • 17
  • 82
  • 82