write and Replace particular line in file

后端 未结 4 1013
刺人心
刺人心 2021-01-19 18:55

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

Input text file contains the following:

#         


        
4条回答
  •  有刺的猬
    2021-01-19 19:47

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

提交回复
热议问题