File write() problem

Tim Roberts timr at probo.com
Sat Dec 30 02:44:47 EST 2006


apriebe47 at gmail.com wrote:

>Alright, I realize this is probably very basic to be posted on this
>newsgroup but I cannot figure out what is causing my problem. Here is
>the code I am using below:
>
>from getpass import getpass
>
>configfile = file('config.txt', 'w')
>serverPassword = configfile.readline()
>    if serverPassword == '':
>        print "Server warning: No password has been set!"
>        pwd1 = getpass("New Password: ")
>        pwd2 = getpass("Confirm Password: ")
>        while pwd1 != pwd2:
>            print "Passwords did not match."
>            pwd1 = getpass("New Password: ")
>            pwd2 = getpass("Confirm Password: ")
>        print "Password set. Storing to file"
>        configfile.write(pwd2)
>        serverPassword = configfile.readline()
>        configfile.close()
>
>Now when I look at the file, I can see the password that I had typed
>in, but there are also a bunch of symbols that are added to the text
>file as well. My question is how can I write just the password to the
>text file and not any extra 'garbage'. Thanks!

You want every file access to start at the beginning of the file.  So,
there is really no point in maintaining a persistent file object at all:

FN = 'config.txt'
serverPassword = open(FN, 'r').readline()
if not serverPassword:
    print "Server warning: No password has been set"
    pwd1 = getpass("New Password: ")
    pwd2 = getpass("Confirm Password: ")
    while pwd1 != pwd2:
        print "Passwords did not match"
        pwd1 = getpass("New Password: ")
        pwd2 = getpass("Confirm Password: ")
    open(FN, 'w').write(pwd2+'\n')
    serverPassword = open(FN, 'r').readline()
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.



More information about the Python-list mailing list