我有一个文件如下
sys.test1.username = user1
sys.test1.pwd = 1234
sys.test2.username = user2
sys.test2.pwd = 1234
我想将 sys.test1.pwd 的密码更改为 sys.test1.pwd = 4321
读取文件
with open (tempfile, 'r') as tempFile:
return self.parse_cfg (self, tempFile.readlines ())
这是搜索 sys.test1.pwd 并获取值。
def parse_cfg (self, lines):
""" Parse ubnt style configuration into a dict"""
ret_dict = {}
for line in lines:
line = line.strip () # remove new lines
if not line: continue # skip empty lines
key, value = line.split ('=') # key = value
print "key %s" %key
if key == 'sys.test1.pwd':
key = key.strip ()
value = value.strip ()
# logic to parse mainkey.subkey.subkey structure into a dict
keys = key.split ('.')
tempo = ret_dict
for each in keys[:-1]:
tempo.setdefault (each, {})
tempo = tempo[each]
tempo[keys[-1]] = value
break
return ret_dict
但我不知道如何将 sys.test1.pwd=4321 写入文件。请帮我