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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Amy G

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

    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_messag e = "blah blah blah"

    f_vm=open("/home/%s/.vacation.msg" %userid, 'r')
    lines=f_vm.read lines()
    f_vm.close()

    if (lines != vacation_messag e):
    f_vm=open("/home/%s/.vacation.msg" %userid, 'w')
    f_vm.writelines (vacation_messa ge)
    f_vm.close()

    Thanks


  • Peter Otten

    #2
    Re: Read from, then write to a file without closing first???

    Amy G wrote:
    [color=blue]
    > 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_messag e = "blah blah blah"
    >
    > f_vm=open("/home/%s/.vacation.msg" %userid, 'r')
    > lines=f_vm.read lines()
    > f_vm.close()
    >
    > if (lines != vacation_messag e):
    > f_vm=open("/home/%s/.vacation.msg" %userid, 'w')
    > f_vm.writelines (vacation_messa ge)
    > f_vm.close()[/color]

    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

    Comment

    • Miki Tebeka

      #3
      Re: Read from, then write to a file without closing first???

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

      HTH.
      Miki

      Comment

      Working...