Read from, then write to a file without closing first???
Peter Otten
__peter__ at web.de
Thu Jan 8 05:39:12 EST 2004
Amy G wrote:
> I am looking to make this code a little "nicer"... any suggestions???
> I want to do a "read+" where I would be able to first read the contents of
> the file... then either close the file out or write to the file without
> appending. I want to overwrite the content.
>
> vacation_message = "blah blah blah"
>
> f_vm=open("/home/%s/.vacation.msg" %userid, 'r')
> lines=f_vm.readlines()
> f_vm.close()
>
> if (lines != vacation_message):
> f_vm=open("/home/%s/.vacation.msg" %userid, 'w')
> f_vm.writelines(vacation_message)
> f_vm.close()
You can open the file in "r+" mode and then f_vm.seek(0) before writing.
However, from the above example I can not see why you even bother to check
the old contents and don't just write the new data.
Peter
More information about the Python-list
mailing list