mr.*_*zog 6 python text editing
我需要在IP地址发生变化时更新文本文件,然后再从shell运行一些命令.
创建变量LASTKNOWN ="212.171.135.53"这是我们编写此脚本时的IP地址.
获取当前的IP地址.它会每天改变.
为新IP创建变量CURRENT.
比较(作为字符串)CURRENT到LASTKNOWN
如果它们相同,则退出()
如果他们不同,
A.将包含LASTKNOWN IP地址的旧配置文件(/etc/ipf.conf)"复制"到/ tmp B.用/tmp/ipf.conf文件中的CURRENT替换LASTKNOWN.
C.使用子进程"mv /tmp/ipf.conf /etc/ipf.conf"D
.使用子进程执行,"ipf -Fa -f /etc/ipf.conf"E
.使用子进程执行,"ipnat -CF -f /etc/ipnat.conf"
出口()
我知道如何执行第1步到第6步.我堕落在"文件编辑"部分,A - > C.我无法分辨使用什么模块或是否应该编辑文件.有很多方法可以做到这一点,我无法决定最好的方法.我想我想要最保守的一个.
我知道如何使用子进程,所以你不需要对它进行评论.
我不想替换整条线; 只是一个特定的点缀四边形
谢谢!
小智 27
简单编辑文件的另一种方法是使用fileinput
模块:
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)
Run Code Online (Sandbox Code Playgroud)
filename = "/etc/ipf.conf"
text = open(filename).read()
open(filename, "w").write(text.replace(LASTKNOWN, CURRENT))
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
注意:"/ tmp/ipf.conf"应替换为tempfile.NamedTemporaryFile()
或类似
注意:代码未经过测试.
fileinput 模块有非常丑陋的 API,我发现这个任务的漂亮模块 - in_place,Python 3 的示例:
import in_place
with in_place.InPlace('data.txt') as file:
for line in file:
line = line.replace('test', 'testZ')
file.write(line)
Run Code Online (Sandbox Code Playgroud)
与文件输入的主要区别:
例如 - fileinput 只能逐行编辑,in_pace 允许将整个文件读取到内存(如果它不大)并修改它。