我有这样的文本文件:
line 1
line 2
line 3
CommandLine arguments "render -h 192.168.1.1 -u user -p pass"
line 5
Run Code Online (Sandbox Code Playgroud)
我想替换IP地址并就地编写文件.棘手的部分是,行可能的顺序不同,命令行参数可能以不同的顺序写入.所以我需要找到以CommandLine开头的行,然后替换-h和下一个之间的字符串-.
到目前为止,我能够使用以下代码获取旧IP地址,但我不知道如何替换它并编写文件.我是Python的初学者.
with open(the_file,'r') as f:
for line in f:
if(line.startswith('CommandLine')):
old_ip = line.split('-h ')[1].split(' -')[0]
print(old_ip)
Run Code Online (Sandbox Code Playgroud) 我需要在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.我无法分辨使用什么模块或是否应该编辑文件.有很多方法可以做到这一点,我无法决定最好的方法.我想我想要最保守的一个.
我知道如何使用子进程,所以你不需要对它进行评论.
我不想替换整条线; 只是一个特定的点缀四边形
谢谢!
如果没有进行字符串替换,Python的string.replace会返回什么?即使没有进行任何更改,Python的file.open(f,'w')是否始终触摸该文件?
使用Python,我试图在一组文件中用'newtext'替换'oldtext'的出现.如果文件包含'oldtext',我想进行替换并保存文件.否则,什么也不做,所以文件保持旧的时间戳.
以下代码工作正常,除非所有文件都被写入,即使没有进行字符串替换,并且所有文件都有新的时间戳.
for match in all_files('*.html', '.'): # all_files returns all html files in current directory
thefile = open(match)
content = thefile.read() # read entire file into memory
thefile.close()
thefile = open(match, 'w')
thefile.write(content.replace(oldtext, newtext)) # write the file with the text substitution
thefile.close()
Run Code Online (Sandbox Code Playgroud)
在这段代码中,我只是在发生字符串替换时尝试执行file.write,但是,所有文件都获得了新的时间戳:
count = 0
for match in all_files('*.html', '.'): # all_files returns all html files in current directory
thefile = open(match)
content = thefile.read() # read entire file into memory
thefile.close()
thefile = open(match, 'w') …Run Code Online (Sandbox Code Playgroud)