Ozgur
Ozgur

Reputation: 172

keep the last value of a variable for the next run

x=0 
for i in range(0,9):
 x=x+1

When I run the script second time, I want x to start with a value of 9 . I know the code above is not logical. x will get the value of zero. I wrote it to be as clear as I can be. I found a solution by saving x value to a txt file as it is below. But if the txt file is removed, I will lose the last x value. It is not safe. Is there any other way to keep the last x value for the second run?

from pathlib import Path

myf=Path("C:\\Users\\Ozgur\\Anaconda3\\yaz.txt")
x=0
if myf.is_file():
 f=open("C:\\Users\\Ozgur\\Anaconda3\\yaz.txt","r")
 d=f.read()
 x=int(d) 
else:        
 f=open("C:\\Users\\Ozgur\\Anaconda3\\yaz.txt","w")
 f.write("0")
 deger=0

for i in range(0,9):
 x=x+1


f=open("C:\\Users\\Ozgur\\Anaconda3\\yaz.txt","w") 
f.write(str(x))  

f.close() 

print(x) 

Upvotes: 0

Views: 365

Answers (2)

ndrwnaguib
ndrwnaguib

Reputation: 6115

You can use databases, they are less likely to be lost than files. You can read about MySQL using Python

However, this is not the only way you can save the value of x. You can have an environment variable in your operating system. As an example,

import os

os.environ["XVARIABLE"] = "9"

To access this variable later, simply use

print os.environ["XVARIABLE"]

Note: On some platforms, modifying os.environ will not actually modify the system environment either for the current process or child processes.

Upvotes: 0

Justine Krejcha
Justine Krejcha

Reputation: 2176

No.

You can't 100% protect against users deleting data. There are some steps you can take (such as duplicating the data to other places, hiding the file, and setting permissions), but if someone wants to, they can find a way to delete the file, reset the contents to the original value, or do any number of things to manipulate the data, even if it takes one unplugging the hard drive and placing it in a different computer.

This is why error-checking is important, because developers cannot make 100% reliable assumptions that everything in place is there and in the correct state (especially since drives do wear down after long periods of time causing odd effects).

Upvotes: 1

Related Questions