edit text file using Python

前端 未结 6 1314
忘了有多久
忘了有多久 2020-12-14 04:55

I need to update a text file whenever my IP address changes, and then run a few commands from the shell afterwards.

  1. Create variable LASTKNOWN = \"212.171.13

6条回答
  •  一个人的身影
    2020-12-14 05:38

    Replace LASTKNOWN by CURRENT in /etc/ipf.conf

    Replace all at once

    filename = "/etc/ipf.conf"
    text = open(filename).read()
    open(filename, "w").write(text.replace(LASTKNOWN, CURRENT))
    

    Replace line by line

    from __future__ import with_statement
    from contextlib import nested
    
    in_filename, outfilename = "/etc/ipf.conf", "/tmp/ipf.conf"
    with nested(open(in_filename), open(outfilename, "w")) as in_, out:
         for line in in_:
             out.write(line.replace(LASTKNOWN, CURRENT))
    os.rename(outfilename, in_filename)
    

    Note: "/tmp/ipf.conf" should be replaced by tempfile.NamedTemporaryFile() or similar
    Note: the code is not tested.

提交回复
热议问题