Overwrite file in python

I am trying to write a file in python so that it saves the latest information read from the serial port. I tried several different methods and read several different messages, but the file continues to write information again and again, without overwriting the previous record.

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 that transmits data wirelessly to a raspberry pi, I just want one line of current data to be saved in the file. right now it just continues the loop and adds it over and over. Any help would be greatly appreciated.

+6
source share
3 answers

I would modify your code to look like this:

 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 cause truncation, redness, etc. Why do not you need to work? :)

+3
source

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

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

Note that truncate() accepts an optional size argument, which you could pass 0, but you still need to go back to the beginning before writing the next part.

+1
source

Before starting to write the file, add the following line:

 outf.seek(0) outf.truncate() 

This will make sure that everything you write overwrites the file

0
source

Source: https://habr.com/ru/post/978530/


All Articles