edit text file using Python
Question: 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!


Answer: Another way to simply edit files in place is to use the
[`fileinput`](http://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&ved=0CC8QFjAA&url=http%3A%2F%2Fdocs.python.org%2Flibrary%2Ffileinput.html&ei=TGeZUPCRHOfP0QXQhIHAAw&usg=AFQjCNEmKT3Z55eqWRpCJIDCDyy1ACOGhg)
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)
    

