File write() problem

rzed rzantow at gmail.com
Wed Dec 27 04:36:01 EST 2006


apriebe47 at gmail.com wrote in
news:1167211184.714069.142290 at h40g2000cwb.googlegroups.com: 

> Marc 'BlackJack' Rintsch wrote:
> 
>> > configfile = file('config.txt', 'w')
>> > serverPassword = configfile.readline()
> 
> Hrm. When I run the code that I posted I don't seem to get those
> errors.
> 
>> Please post the exact code you have trouble with.  Don't retype
>> it -- copy and paste it.
> 
> 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 admin/config..."
>    configfile.write(pwd2)
>    serverPassword = configfile.readline()
>    configfile.close()
> 
> Again I tested the code before I posted and I get no errors,
> just not the result I am looking for in the text file. Thanks
> for taking the time to look at it.
> 

As Marc points out, you are opening the file in write mode and 
then reading from it. Did you try printing out what gets placed 
into serverPassword the first time? It may not be what you expect, 
for starters. But now the file pointer is at the end of the file, 
and that's where you write the input password. Amazingly, Python 
lets you do this, but even if you could read back those characters 
you just wrote by doing a readline() (which might be getting data 
from the ether by now), the password wouldn't be written over the 
original, but instead would be on the next line.

If your intent is to update a flat file, you can try using seeks 
and rewinds and such to position the file pointer appropriately, 
but you'll still be in misery as soon as someone replaces the 
password "G811ploo" with "ALongerPassword". Flat files aren't 
databases. You're better off reading the entire file (opened in 
read mode) into memory and closing it, then re-opening it in write 
mode and writing out the entire thing with the changed password, 
replacing the original file.

-- 
rzed
... for some value of better off...




More information about the Python-list mailing list