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

Discussion in 'Python' started by Amy G, Jan 8, 2004.

  1. Amy G

    Amy G Guest

    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
    Amy G, Jan 8, 2004
    #1
    1. Advertising

  2. Amy G

    Peter Otten Guest

    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
    Peter Otten, Jan 8, 2004
    #2
    1. Advertising

  3. Amy G

    Miki Tebeka Guest

    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
    Miki Tebeka, Jan 8, 2004
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. matt
    Replies:
    9
    Views:
    405
    Andrew Thompson
    Oct 27, 2004
  2. Roy Gourgi

    Write and then read from a file

    Roy Gourgi, Jul 14, 2005, in forum: C++
    Replies:
    5
    Views:
    321
    Paul Groke
    Jul 15, 2005
  3. Mufasa
    Replies:
    7
    Views:
    407
    Alexey Smirnov
    Sep 4, 2007
  4. Replies:
    0
    Views:
    261
  5. thomas
    Replies:
    0
    Views:
    218
    thomas
    Oct 23, 2003
Loading...

Share This Page