1
your_data = {'rose': 'red',
         'sun': 'orange',
         'sky': 'blue'}

with open('save.txt','w') as f:
while True:
    print(your_data, file=f)

This is an sample program. here the dictionaries are copied to the file named save.txt. Actually I am running this program in raspberry pi and if the power suddenly gets off, the datas stored completely gets erased. I want my program to start again from the previous end of the program or I should have an backup from where I can restart my program.

  • I'm thinking that this is impossible `if the power suddenly gets off`. I would love to be proved wrong. – quamrana May 14 '18 at 15:33
  • 1
    @quamrana surely it's not impossible? They could just store checkpoints into files whenever needed, then check that file for a specific checkpoint and run from there. Although i'm really not sure what they're asking so I may have misunderstood. – Sasha May 14 '18 at 15:35
  • @Jaxi: That would be my guess for a solution too, but just because python executes code which appends data to a file, how do you know it has been stored in the face of a power failure? – quamrana May 14 '18 at 15:39
  • @quamrana Raspberry Pi's operate on very low power which allows them to be powered by rather 'sketchy' power sources. Since it is such a small device it is highly portable and is often not used in stationary cases... this means that the power can quite often be disconnected. – Trevor Clarke May 14 '18 at 15:39
  • https://stackoverflow.com/questions/7127075/what-exactly-the-pythons-file-flush-is-doing https://stackoverflow.com/questions/3167494/how-often-does-python-flush-to-a-file – Josh Lee May 14 '18 at 15:51

1 Answers1

0

If your program terminates abruptly, buffered output might not make it from your program to the operating system. If power is cut, buffered output might not make it from the operating system to disk.

The first is handled with flush on the file object, and the second by fsync in the io module.

f.flush()
os.fsync(f.fileno())

This is somewhat slow, of course. You can also use open('file.txt', 'w', buffering=0) to eliminate buffered IO and skip the need to flush (but you will still need to fsync).

(Even so, there are still no guarantees: Hard drives are known to report that a write has completed when it is actually on volatile storage inside the hard drive.)

How your program recovers after being interrupted is an entirely different matter. Perhaps it can read the output file to determine where it left off. (When resuming your writes, remember to use append 'a' mode so as not to truncate your output file.)

Also try the sqlite3 module: The underlying SQLite database is robust against power failures.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275