Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change variable permanently

I'm writing a small program that helps you keep track of what page you're on in your books. I'm not a fan of bookmarks, so I thought "What if I could create a program that would take user input, and then display the number or string of text that they wrote, which in this case would be the page number they're on, and allow them to change it whenever they need to?" It would only take a few lines of code, but the problem is, how can I get it to display the same number the next time I open the program? The variables would reset, would they not? Is there a way to permanently change a variable in this way?

like image 451
MalyG Avatar asked Dec 11 '12 23:12

MalyG


1 Answers

You can store the values in a file, and then load them at start up.

The code would look somewhat like this

variable1 = "fi" #start the variable, they can come from the main program instead
variable2 = 2

datatowrite = str(variable1) + "\n" + str(variable2) #converts all the variables to string and packs them together broken apart by a new line

f = file("/file.txt",'w')
f.write(datatowrite) #Writes the packed variable to the file
f.close() #Closes the file !IMPORTANT TO DO!

The Code to read the data would be:

import string

f = file("/file.txt",'r') #Opens the file
data = f.read() #reads the file into data
if not len(data) > 4: #Checks if anything is in the file, if not creates the variables (doesn't have to be four)

    variable1 = "fi"
    variable2 = 2
else:
    data = string.split(data,"\n") #Splits up the data in the file with the new line and removes the new line
    variable1 = data[0] #the first part of the split
    variable2 = int(data[1]) #Converts second part of strip to the type needed

Bear in mind with this method the variable file is stored in plaintext with the application. Any user could edit the variables and change the programs behaviour

like image 157
DeadChex Avatar answered Oct 02 '22 16:10

DeadChex