简体   繁体   中英

Not able to store the data in a file using python

I am trying to print the serial data to a file using python script. When I run the below code I dont see any data in the file. However I see the data in the python output editor. Why I am unable to save to the file?. I tried adding the delay also. No use. I dont see any mistake in file creation and appending data to file. Can someone suggest the changes?. Thank you.

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 = 115200 ## 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)
    print(line)
    f.write(line+"\r\n")    # Appends output to file

It seems that the file is not closing at any point and because of that the write method is not getting store in the file, you can use with in the loop and it will store the data in each iteration

while True:
    with open("data_file.txt", "a") as f:
        s = ser.readline()
        line = s.decode('utf-8').replace('\r\n', '')
        time.sleep(.1)
        print(line)
        f.write(line + "\r\n")

Adding

f.close()

to the above code worked like a charm. Thank you Leo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM