r/pythonhelp • • Oct 28 '20

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

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 hard coded .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 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

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

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

```

anything helps thank you in advanced

3 Upvotes

1 comment sorted by

1

u/someoneonboard1 Oct 28 '20 edited Oct 28 '20

Open output file first by doing:

with open(output_filename) as outputfile:

with open(test_file) as file_test:

send command to serial

rcv_data = data from serial

outputfile.write(rcv_data+’\n’)