0

I want to save configuration of an application written in Python 2 to a file (I have to choose the file format, JSON, SQL, Pickle...).

I know this is a simple task, but I want to do it reliably. I'd like to save two identical copies of the file, check the integrity of the main file and, if needed (main is corrupted), load data from the aux file.

However I don't know how to check the integrity of a file. Any suggestion?

pozzugno
  • 750
  • 6
  • 19
  • 2
    The "integrity" of the file is whatever you want it to be. Identify what properties *you* need the file to have, and check for those. – Scott Hunter Jan 10 '20 at 14:20
  • 2
    This question is opinion based. As @ScottHunter says, integrity can be anything. You could go over each character in each file and make sure they are all similar. You could do a [checksum](https://en.wikipedia.org/wiki/Checksum) and compare file sizes. You could choose specific properties within your e.g. `JSON` and see if those are similar. What is it you are trying to accomplish? – DUDANF Jan 10 '20 at 14:38
  • What happens if during saving the process is aborted? At next startup the app will not have a good configuration file to load. In this case, the aux configuration file, even if it's old, can be used to launch the app with a good configuration. – pozzugno Jan 10 '20 at 14:54

2 Answers2

0

I would use 3 files and hash them before reading. When all 3 hashes are equal, you know that everything is fine. If 1 hash isn't the same as the other two, you know that you have to read one of the two equal files. When all three hashes are different, at least two of the files are corrupted. Use this link Hashing a file in Python to learn how to calculate the hash of a file.

bb1950328
  • 1,403
  • 11
  • 18
0

One possible solution is python-atomicwrites module.

pozzugno
  • 750
  • 6
  • 19