简体   繁体   中英

Edit python global variable defined in different file

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.

Try this Create a file called tvseries with these contents:

Murder I Wrote
Top Gear

file1.py :

with open("tvseries", "r") as f:
    tvseries = map(str.strip, f.readlines())

def save(tvseries):
    with open("tvseries", "w") as f:
        f.write("\n".join(tvseries))

file2.py :

import file1

print file1.tvseries[0]
file1.tvseries.append("Dr Who")
file1.save(file1.tvseries)

I've moved the contents of your init method out to module level since I don't see any need for it to exist. When you import file1 any code at the module level will be automatically run - eliminating the need for you to manually run file1.init() . I've also changed the code to populate the contents of tvseries by reading from a simple text file called tvseries containing a list of tv series and added a save method in file1.py which will write the contents of it's argument to the file tvseries .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM