我有两个文件config.py
,其中编写脚本以读写字典& dict.py
包含字典。我想在key('server')
中找到dict.py
并将其中的一个键替换为某个值。请注意,现有的其他键应该存在,只应替换server['hostname']
字段。有人告诉我如何这可以做到,我尝试了以下方式
server = {'hostname': 'ocm-server-31.com',
'user': 'root',
'password': 'radia123'
}
in_servers = {
'robotwin': {'user': 'root',
'esxiuname':'root',
'esxipwd':'gone2far',
'vmname':'robot12_221'
}
}
csa_server = {'hostname': 'opsware.com',
'user': 'admin',
'password': 'cloud'
}
server = {'hostname': 'hyi01lr0bsaehost.com',
'user': 'root',
'password': 'opsware',
}
with open('dict.py','r') as f_in, open('dict.py','w') as f_out:
for line in f_in :
if line['server'] == 'server':
replace_text = f_out.replace(server['hostname'])
print "Text found "
else:
print "Text not found "
答案 0 :(得分:0)
# Replace variables in file
with open('conf.py', 'r+') as f:
content = f.read()
f.seek(0)
f.truncate()
for line in content:
f.write(content.replace('search_text', 'new_text'))