7

I'm trying to over write a file in python so it only keeps the most up to date information read from a serial port. I've tried several different methods and read quite a few different posts but the file keeps writing the information over and over with out overwriting the previous entry.

 import serial

 ser=serial.Serial('/dev/ttyUSB0',57600)

 target=open( 'wxdata' , 'w+' )

 with ser as port, target as outf:
      while 1:
           target.truncate()
           outf.write(ser.read))
           outf.flush()

I have a weather station sending data wirelessly to a raspberry pi, I just want the file to keep one line of current data received. right now it just keeps looping and adding over and over. Any help would be greatly appreciated..

3 Answers3

3

I would change your code to look like:

from serial import Serial

with Serial('/dev/ttyUSB0',57600) as port:
    while True:
        with open('wxdata', 'w') as file:
            file.write(port.read())

This will make sure it gets truncated, flushed, etc. Why do work you don't have to? :)

Travis Griggs
  • 21,522
  • 19
  • 91
  • 167
1

By default, truncate() only truncates the file to the current position. Which, with your loop, is only at 0 the first time through. Change your loop to:

while 1:
    outf.seek(0)
    outf.truncate()
    outf.write(ser.read())
    outf.flush()

Note that truncate() does accept an optional size argument, which you could pass 0 for, but you'd still need to seek back to the beginning before writing the next part anyway.

Cameron
  • 96,106
  • 25
  • 196
  • 225
0

Before you start writing the file, add the following line:

outf.seek(0)
outf.truncate()

This will make it so that whatever you write next will overwrite the file

Vedaad Shakib
  • 739
  • 7
  • 20
  • Careful with this in general -- if what you write next is shorter than what was there before, only the start of the file will be overwritten! The call to `truncate()` is necessary too. – Cameron Nov 21 '14 at 23:00