pythonpython-2.7

Trying to write to a .txt file using "a" says file is not open for writing


I'm new to python and so I'm trying to make an ATM (simulator I guess). One of the functions is to register, and so I'm trying to save the usernames in a .txt file for reference (passwords will come later of course), but for some reason it won't work.

def atm_register():
    print "To register, please choose a username."

    username = raw_input('> ')

    with open("users.txt") as f:
        f.write(username, "a")

It tells me, that the file is not open for writing. Btw, the users.txt file is in the same directory as the program.


Solution

  • Given that you're calling f.write(username, "a") and file write() only takes one parameter - the text to write - I guess you intend the "a" to append to the file?

    That goes in the open() call; other answers telling you to use open(name, "w") are bad advice, as they will overwrite the existing file. And you might want to write a newline after the username, too, to keep the file tidy. e.g.

    with open("users.txt", "a") as f:
        f.write(username + "\n")