Live Write to File with Code That is Reading File and Writing to Serial Port

Karen Shaeffer klsshaeffer at icloud.com
Wed Oct 28 10:58:31 EDT 2020


> On Oct 28, 2020, at 5:49 AM, ktkelly_1 <kjk562 at gmail.com> wrote:
> 
> Currently have a code that takes in a .txt file and submits commands to the serial. Then it reads the reply from the serial port and writes it to a hardcoded .txt file. The problem is it doesn't save it live and so if I need to stop the code for any reason, I can't gather current data and the text file is blank. I'm not as familiar with buffering and things like that and tried "outputFile = open("./outputFile.txt", "a", 0)" but that gave me the error "can't have an unbuffered text I/O” in python 3?" so I'm not sure what to do. Here is the general layout if you would like to mess around with it:

from os import fsync
> with open(test_file) as file_test:
>    Lines = file_test.readlines()
>    for line in Lines:
>        #send_str is the command to send to the serial port
>        send_str = line
>        file_result.write(line + "\n")   #<--- if I were to cancel out after this it wouldn't be saved(*)

file_result.flush()
os.fsync()

>                
>        ser.write(send_str.encode('utf-8'))
>        time.sleep(send_pause)
>        reply_str = ser.readline().decode('utf-8').strip()
>        file_result.write("reply:" + reply_str + "\n")   #<---(*)
>        file_result.write('\n')   #<---(*)
file_result.flush()
os.fsync()


Karen



More information about the Python-list mailing list