Best practice for persistent data storage?

First, on some background, I have a python script that will be called periodically by the cron task. I have an integer variable in a script that should increment every time a cron job calls a python script.

Example: each environment will increase the number of variables (75, 76, etc.). I tried to create a link file outside the script using Python I / O , however the options that I open do not really help me.

w + : opens a file for writing and reading. Overwrites an existing file if the file exists. If the file does not exist, a new file is created for reading and writing.

This option will work if every time the file is opened, it is not overwritten. Value when script tries to add 1 to reading from file, just null

r + : opens a file for reading and writing. The file pointer will be at the beginning of the file.

This parameter will work if it does not just add the newly calculated number to the beginning of the file, and then next time it will read the total amount of the new number and the previous number:

instead of reading 71 on the second run, he reads 7170

There is probably a much better way to store data outside of a script that I don't know about. Thanks.

+4
source share
1 answer

You want r+ . However, before writing, you want seek(0) , so you start writing from the beginning of the file, not where you stopped reading.

You can also open the file twice, once for reading and once for writing, but this is inefficient.

+2
source

Source: https://habr.com/ru/post/1442802/


All Articles