我想替换键的值(即db_host
, addons_path
) with $$$$
.
输入文本文件包含以下内容:
#Test.txt#
addons_path=/bin/root
admin_passwd = abctest
auto_reload = False
csv_internal_sep = ,
db_host = 90.0.0.1
输出文本文件:
#Test2.txt#
admin_passwd = abctest
auto_reload = False
csv_internal_sep = ,
db_host = $$$$$
我想替换特定键的值并将其写入文件中,而不是用新文件替换旧文件。
以下函数为我提供了替换特定键的值的正确输出
导入文件输入
从 pprint 导入 pprint 作为 p
replace_with = '7777'
key = 'db_host'
fileref = open('/Files/replace_key/test','r+')
line = fileref.readline()
config = []
while line:
split_line = line.split('=')
if len(split_line ) == 2:
config.append( ( split_line[0].strip(' \n'),split_line[1].strip(' \n') ) )
print line
line = fileref.readline()
fileref.close()
config = dict(config)
print config
config.update({'db_host':replace_with})
p(config)
但我无法将其应用于整个文本文件。
如果您想使用 Python 执行此操作,可以使用以下函数:
def replace_in_file(filename, key, new_value):
f = open(filename, "r")
lines = f.readlines()
f.close()
for i, line in enumerate(lines):
if line.split('=')[0].strip(' \n') == key:
lines[i] = key + ' = ' + new_value + '\n'
f = open(filename, "w")
f.write("".join(lines))
f.close()
replace_in_file("file.txt", 'db_host', "7777")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)