Issue
We are acquiring data from an Arduino strain gauge through the serial port of the Raspberry Pi and Python. We have it so it will read all the data do the necessary calculations and it will print to a text file however if there is a power failure the data gathered is lost. This is what we are trying to figure out how to fix or not have happen.
import serial
ardserial = serial.Serial('/dev/ttyACM0',9600)
counter = 1
def strain():
a=int(adserial.readlines())
b=(str(a*(5/16)/166))
c=float(b)
with open('textfile1.txt','a+') as text_file:
text_file.write('Strain Value: ' + str(c) + '\n')
while counter > 0:
strain()
We have it so it will write to the txt file correctly and it will save all the data if we kill the program but we also expected it to save all the data if the power was pulled to the Raspberry Pi. It does not do this.
I was almost 100% sure that I have done it in the past where if the power was killed it would have the saved data but I can't for the life of me figure it out. Any help would be... well... helpful thanks.
Solution
Write data to disk after each file write:
If you’re starting with a buffered Python file object f, first do f.flush(), and then do os.fsync(f.fileno()), to ensure that all internal buffers associated with f are written to disk.
Source: Python docs
Answered By - VPfB Answer Checked By - Willingham (WPSolving Volunteer)