我正在使用python 3.6制作一个小的“保存配置文件”脚本,其中字典是要保存的配置文件。它有两个函数来保存配置文件(字典)并使用pickle模块加载一个。
import pickle
profile = {'a':1,'b':2,'c':3}
loadedProfile = {}
def saveProfile():
profileName = input("Save profile as ... ")
save = open(profileName + ".pickle","wb")
pickle.dump(profile,save)
save.close()
def loadProfile():
profileName = input("Opem profile ... ")
load = open(profileName + ".pickle","rb")
loadedProfile = pickle.load(load)
load.close()
print(loadedProfile)
saveProfile()
loadProfile()
print(loadedProfile)
输出:
{'a': 1, 'b': 2, 'c': 3}
{}
请注意,在函数内部,它将loadedProfile打印为旧字典,但函数外的第二个打印件会打印一个空字典。
什么阻止字典数据被保存到函数内的字典中?
谢谢。
答案 0 :(得分:3)
问题在于:当你这样做时:
loadedProfile = pickle.load(load)
您正在创建一个与全局变量同名的局部变量(退出该函数时该变量将丢失)。您需要告诉python您将重用相同的名称
global loadedProfile
loadedProfile = pickle.load(load)
就个人而言,我会返回这样的变量。依赖全局变量通常是一个坏主意(对于保存功能也是如此):
import pickle
profile = {'a':1,'b':2,'c':3}
def saveProfile(p):
profileName = input("Save profile as ... ")
with open(profileName + ".pickle","wb") as save:
pickle.dump(p,save)
def loadProfile():
profileName = input("Opem profile ... ")
with open(profileName + ".pickle","rb") as load:
loadedProfile = pickle.load(load)
return loadedProfile
saveProfile(profile)
new_profile = loadProfile()