Python Forum

Full Version: Reading serial data and saving to a file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi ,
I am trying to read a serial data and save that in a file. I could not print any data to the file.

from __future__ import print_function
import serial, time, io, datetime
from serial import Serial
import time

addr = "COM5" ## serial port to read data from
baud = 921600 ## baud rate for instrument

ser = serial.Serial(
    port = addr,\
    baudrate = baud,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
    timeout=0)


print("Connected to: " + ser.portstr)
filename="data_file.txt"
f   = open("data_file.txt", "a")

while True:
    s    = ser.readline()
    line = s.decode('utf-8').replace('\r\n','')
    time.sleep(.1)
    f.write(line+"\r\n")	# Appends output to file
Can someone help me. Thank you.
Please use proper code tags while posting your thread, it will be much easier to understand. See BBCode to know more