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

Terry Reedy tjreedy at udel.edu
Wed Oct 28 19:14:20 EDT 2020


On 10/28/2020 8:49 AM, ktkelly_1 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:

> 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

Both input and output should be controlled by the with statement.  Same 
for serial port?  Open files are line iterables. readlines is only 
needed if you need the whole file at once.  Two names for the same line 
is a buglet.

with open(test_file) as f_in, open(results) as f_out:
     for command in f_in:  # Sent to serial port

>          file_result.write(line + "\n")   #<--- if I were to cancel out after this it wouldn't be saved(*)

Do you really want a command at the end of the file without results?  If 
not, write command and result in one write after getting result.

>          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')   #<---(*)


-- 
Terry Jan Reedy




More information about the Python-list mailing list