Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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)
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!