First some background, I have a python script that will be called periodically by a cron job. I have a integer variable in the script that will need to increase every time the cron job calls the python script.
Example, every Wednesday will increase the count of the variable (75, 76, etc.) I’ve tried to create a reference file outside of the script using Python I/O however the options I have opening the file don’t really help me.
w+ : Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
This option would work if everytime the file was opened it didn’t overwrite itself. Meaning when the script attempts to add 1 to what’s read from the file it’s simply null
r+ : Opens a file for both reading and writing. The file pointer will be at the beginning of the file.
This option would work if it didn’t simply add the newly computed number to the beginning of the file, and then the next time it will read the total amount of the new number and previous number:
instead of reading 71 on the 2nd run through, it reads 7170
There’s probably a much better way to store data outside of the script that I’m unaware of.
Thanks.
You want
r+. However, you want toseek(0)before writing, so you start writing from the beginning of the file rather than where you stopped reading.You could also open the file twice, once for reading and once for writing, but that’s inefficient.