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

时间:2014-05-21 11:39:25

标签: python python-2.7 python-3.x

我想用db_host替换密钥(即addons_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     来自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 :(得分:1)

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

答案 1 :(得分: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. 使用=作为键/值分隔符写出字典。
  4. 享受:)

    更新:作为一组可重复使用的功能:

    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 :(得分: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)

答案 3 :(得分: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'),