Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...