写入和替换文件中的特定行 [英] write and Replace particular line in file

查看:51
本文介绍了写入和替换文件中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 $$$$ 替换键的值(即 db_host, addons_path).

I want to replace value of key(i.e db_host, addons_path) with $$$$.

输入文本文件包含以下内容:

Input text file contains the following:

#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 = $$$$$

我想替换特定键的值并将其写入文件,而不是用新文件替换旧文件.

I want to replace value of particular key and write it in a file, than replace old file with new file.

以下函数为我提供了替换特定键值的正确输出导入文件输入from pprint import pprint as p

The following function gives me correct output of replacing value of particular key import fileinput from pprint import pprint as 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)

但我无法将其应用于整个文本文件.

But I am unable apply it to entire text file.

推荐答案

如果你想用 Python 做到这一点,你可以使用以下函数:

If you want to do that with Python, you can use the following function:

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")

这篇关于写入和替换文件中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆