Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

edit text file using Python

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.135.53" This is the ip address we have while writing this script.

  2. Get the current IP address. It will change on a daily basis.

  3. Create variable CURRENT for the new IP.

  4. Compare (as strings) CURRENT to LASTKNOWN

  5. If they are the same, exit()

  6. If they differ,

    A. "Copy" the old config file (/etc/ipf.conf) containing LASTKNOWN IP address into /tmp B. Replace LASTKNOWN with CURRENT in the /tmp/ipf.conf file.
    C. Using subprocess "mv /tmp/ipf.conf /etc/ipf.conf"
    D. Using subprocess execute, "ipf -Fa -f /etc/ipf.conf"
    E. Using subprocess execute, "ipnat -CF -f /etc/ipnat.conf"

  7. exit()

I know how to do steps 1 through 6. I fall down on the "file editing" part, A -> C. I can't tell what module to use or whether I should be editing the file in place. There are so many ways to do this, I can't decide on the best approach. I guess I want the most conservative one.

I know how to use subprocess, so you don't need to comment on that.

I don't want to replace entire lines; just a specific dotted quad.

Thanks!

like image 988
mr.zog Avatar asked Oct 17 '09 17:10

mr.zog


2 Answers

Another way to simply edit files in place is to use the fileinput module:

import fileinput, sys
for line in fileinput.input(["test.txt"], inplace=True):
    line = line.replace("car", "truck")
    # sys.stdout is redirected to the file
    sys.stdout.write(line)
like image 174
Tim Jones Avatar answered Oct 14 '22 06:10

Tim Jones


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.

like image 37
jfs Avatar answered Oct 14 '22 04:10

jfs