Read from, then write to a file without closing first???

A

Amy G

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()

Thanks
 
P

Peter Otten

Amy said:
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
 
M

Miki Tebeka

Hello Amy,
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.
def check(file, msg):
if open(file).read() != msg:
open(file, "w").write(msg)

HTH.
Miki
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top