在文件中写入并替换特定行

4 投票
4 回答
6497 浏览
提问于 2025-04-18 07:12

我想把某些键(比如 db_hostaddons_path)的值替换成 $$$$

输入的文本文件内容如下:

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

我想替换特定键的值,然后把它写入一个文件,最后用新文件替换旧文件。

下面这个函数可以正确地替换特定键的值:

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)

但是我无法将它应用到整个文本文件上。

4 个回答

0

使用 fileinput 模块。

import fileinput

for line in fileinput.input('data.txt',backup='.bak',inplace=1):
    print line.rstrip().replace('Python','Perl') 
    #or print line.replace('Python','Perl'),
0

那这样做怎么样呢?

def replace_string(s):
    s = s.replace('db_host','$$$$')
    return s
with open('test.txt','r') as fo:
    line = fo.read() # you could use strip() or split() additionally
new_string = replace_string(line)
0

用UNIX工具来做这个事情要简单得多。

不过,这里是我的解决方案:

bash-4.3$ cat - > test.txt
#Test.txt#
addons_path=/bin/root
admin_passwd = abctest
auto_reload = False
csv_internal_sep = ,
db_host = 90.0.0.1
bash-4.3$ python
Python 2.7.6 (default, Apr 28 2014, 00:50:45) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> with open("test.txt", "r") as f:
...     pairs = (line.split("=", 1) for line in f if not line.startswith("#"))
...     d = dict([(k.strip(), v.strip()) for (k, v) in pairs])
... 
>>> d["db_host"] = "$$$$"
>>> with open("out.txt", "w") as f:
...     f.write("\n".join(["{0:s}={1:s}".format(k, v) for k, v in d.items()]))
... 
>>> 
bash-4.3$ cat out.txt
db_host=$$$$
admin_passwd=abctest
auto_reload=False
csv_internal_sep=,
addons_path=/bin/rootbash-4.3$ 
  1. 读取文件,并通过=将里面的键值对解析成一个dict忽略注释)。
  2. 在得到的字典中修改db_host这个键。
  3. 使用=作为键值分隔符,把字典写出来。

希望你喜欢 :)

更新:作为一组可重用的函数:

def read_config(filename):
    with open(filename, "r") as f:
        pairs = (line.split("=", 1) for line in f if not line.startswith("#"))
        return dict([(k.strip(), v.strip()) for (k, v) in pairs])


def write_config(d, filename):
    with open(filename, "w") as f:
        f.write("\n".join(["{0:s}={1:s}".format(k, v) for k, v in d.items()]))
2

如果你想用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")

撰写回答