Changing variables of imported module doesnt seem to work. [Python]

I am trying to make a separate dictionary in a python file, so I could import it and do stuff such as search key, add word, remove word. The file is dictionary.py . It contains:

#-*-coding:utf8-*-
dict={}

So when I import it in my main python file, add a word and print it, it works fine, but the dictionary.py file doesn't gets affected. I want the "dict" variable in dictionary.py file to change too. Here's my code for the main file:

import os
import sys
import dictionary as tdict
print ":::::::::::::::::::"
print "Add word"
print ":::::::::::::::::::"
name=raw_input("Word: ")
print
mean=raw_input ("Meaning: ")
tdict.dict[name]=mean
print "::::Word added::::"
print
print "::::::::::::::::::::::"
print "Dictionary:"
print
for x in tdict.dict:
    print "",x,":",tdict.dict[x]`

Any help? thx


You are not writing to the file at any point. The correct way to store a python object such as a dictionary is to use pickle :

import pickle


myDictionary = {}
dictionaryFile = open('dictionary', 'wb')
pickle.dump(mydictionary, dictionaryFile)
dictionaryFile.close()

This will create a pickle file called dictionary that contains myDictionary

To read the dictionary:

import pickle


dictionaryFile = open('dictionary', 'rb')
myDictionary = pickle.load(dictionaryFile)
dictionaryFile.close()

Then you can make whatever changes you want to the dictionary then save it to the file again:

import pickle


dictionaryFile = open('dictionary', 'rb')
myDictionary = pickle.load(dictionaryFile)
dictionaryFile.close()

myDictionary['key1'] = 'value1'

dictionaryFile = open('dictionary', 'wb')
pickle.dump(mydictionary, dictionaryFile)
dictionaryFile.close()
链接地址: http://www.djcxy.com/p/55080.html

上一篇: 使用python执行一个linux命令

下一篇: 更改导入模块的变量似乎不起作用。 [蟒蛇]