write and Replace particular line in file

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

    What about something like this ?

    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 讨论(0)
  • 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()]))
    
    0 讨论(0)
  • 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")
    
    0 讨论(0)
  • 2021-01-19 19:49

    use fileinput module.

    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 讨论(0)
提交回复
热议问题