I am using this code to read values from a serial port and writing it to a text file
import serial
ser = serial.Serial("/dev/ttyUSB0", 9600)
text_file = open("output.txt", 'w')
while ser.read():
x=ser.read()
print(x)
text_file.write(x)
text_file.flush()
text_file.close()
ser.close()
This code is working and values are appended in the textfile. Is there any way to overwrite the text file when each value is received serially i.e only the last value need to be stored in the textfile. The ser.read() creates an infinite loop so the only way to stop the code is by using a key board interrupt(ctrl+z) but while using this the textfile and the serial connection remains unclosed ,how can i solve this?