2

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?

2 Answers 2

3

You can truncate the file just before you write to it. That way it will adhere to storing the value when each value is received serially as you requested. Slightly modifying your code,

import serial
ser = serial.Serial("/dev/ttyUSB0", 9600)
text_file = open("output.txt", 'w')
while ser.read():
     x=ser.read()
     print(x)
     test_file.seek(0)
     text_file.truncate()    
     text_file.write(x)
     text_file.flush()
text_file.close()
ser.close()

That way your file will maintain the most recent value - check this with tail -F otuput.txt.

Sign up to request clarification or add additional context in comments.

Comments

2
from serial import Serial
with (open("output.txt", 'w'), Serial("/dev/ttyUSB0", 9600)) as text_file, ser:
     while ser.read():
          x=ser.read()
          print(x)    
     text_file.write(x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.