write and Replace particular line in file

后端 未结 4 1018
刺人心
刺人心 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:46

    This is much simpler achieved with UNIX tools.

    Nevertheless here's my solution:

    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. Read the file and parse it's key/value pairs by = into a dict (ignoring comments).
    2. Change the db_host key in the resulting dictionary.
    3. Write out the dictionary using = as key/value separators.

    Enjoy :)

    Update: As a reuseable set of functions:

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

提交回复
热议问题