I am using Python 2.7. I want to store a variable so that I can run a script without defining the variable in that script. I think global variables are the way to do this although I am open to correction.
I have defined a global variable in file1.py:
def init():
global tvseries
tvseries = ['Murder I Wrote','Top Gear']
In another file, file2.py, I can call this variable:
import file1
file1.init()
print file1.tvseries[0]
If I edit the value of file1.tvseries (file1.tvseries[0] = 'The Bill') in file2.py this is not stored. How can I edit the value of file1.tvseries in file2.py so that this edit is retained?
EDIT: Provide answer
Using pickle:
import pickle
try:
tvseries = pickle.load(open("save.p","rb"))
except:
tvseries = ['Murder I Wrote','Top Gear']
print tvseries
tvseries[0] = 'The Bill'
print tvseries
pickle.dump(tvseries,open("save.p", "wb"))
Using json:
import json
try:
tvseries = json.load(open("save.json"))
tvseries = [s.encode('utf-8') for s in tvseries]
except:
tvseries = ['Murder I Wrote','Top Gear']
print tvseries
tvseries[0] = str('The Bill')
print tvseries
json.dump(tvseries,open("save.json", "w"))
Both these files return ['Murder I Wrote','Top Gear']['The Bill','Top Gear'] when run the first time and ['The Bill','Top Gear']['The Bill','Top Gear'] when run the second time.
file2.py.file2.pyto actually change the scriptfile1.py? Why don't you store the "global variable" in a text file (e.g. using JSON orpickle) instead? What's the point in it being defined in a Python file?tvseries[0]to'Murder I Wrote'. Look at thepickleormarshallor evenjsonmodules instead; save the data in a separate file and re-save it each time the data changes.