Write and close file before unexpected system shutdown on a Raspberry pi

Viewed 123

I have a rc522 RFID card Reader connected to my Raspberry pi 3. I have written a Python program that writes the cardnumber of the logged card to a file. That is working nice. I have also made a "systemd service" that starts this Python program on system startup. That's working fine too. It writes the cardnumbers to the file. But only after the system shuts down normally. When the system shutdown unexpectedly the card numbers are not written to the file. I can log cards the whole day but when the system shuts down unexpected all card numbers I have logged are gone. This happens only when the program is started by the "systemd service". When I start the program myself it writes all to the file immediately. That's also the case when the system shuts doen unexpected. All cardnumbers has then been written to the file. I assume that when the program is started by the systemd service the logged cardnumbers stay in memory until the system shuts down normally. Is there a way I can force the writing to file when it's started by the systemd service and not kept in memory? I have also tried it with a crontab job but that has the same problem. The code for writing to file is:

with open(path and filename, "a") as file:
    file.write(cardnumber)
1 Answers

The answer to my problem was as @stark stated. I had indeed to flush() the file. But I also had to add after that commmand the command "os.fsync()". And that last command is essential. Otherwise the flush won't activated. That answer I found in this question on Stackoverflow: how often does python flush to file Now when I add a cardnumber and immediatly after that the system unexpectacly powers down that cardnumber was written to file. My code looks now like this:

with open('path and filename', 'a') as file:
   file.write('text\n')
   file.flush()
   os.fsync(file)
Related