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

Python 写入并替换文件中的特定行,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我想用$$替换键的值(即db\u host,addons\u 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\u host
addons\u 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 = $$$$$
我想替换特定密钥的值并将其写入文件,而不是用新文件替换旧文件

以下函数为我提供了替换特定键值的正确输出 导入文件输入 从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")

使用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$ 
  • 读取文件并通过
    =
    将其键/值对解析为
    dict
    (忽略注释)
  • 在生成的字典中更改
    db\u host
  • 使用
    =
    作为键/值分隔符写出字典
  • 享受:)

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

    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()]))
    

    像这样的怎么样

    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)
    

    使用
    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'),
    

    sed-i的/^db\u主机=.*$/db\u主机=$$$$$$/'test.txt
    或者:
    sed-i的:^\(db\u主机|加载项路径).*$:$1=$$$$:gm'test.txt