当我运行下面的代码时,我没有得到预期的输出。 请纠正我。。你知道吗
import socket
import re
NodeName=socket.gethostname()
change_hostname_list=['/etc/hosts1','/etc/sysconfig/network1']
for file in change_hostname_list:
infile=open(file,'r').read()
print NodeName
print file
if re.search('NodeName',file):
print "DOOO"
我需要输出“DOOO”
我得到下面的那个
root@test06> python test.py
test06
/etc/hosts1
test06
/etc/sysconfig/network1
root@test06>
删除引号如果NodeName是字符串它应该只做字符串搜索文件。你知道吗
如果您需要使用一些正则表达式,您可以连接变量来创建正则表达式字符串并将其传递给
re.search
。你知道吗另外,如果您不需要任何正则表达式的东西,只需要简单的旧子字符串搜索,您可以使用字符串函数
find
,用法如下:您似乎将字符串
'NodeName'
作为模式传递给re.search()
,而不是变量NodeName
。删除您提供的代码第9行中的单引号。你知道吗替换此项:
收件人:
变量不需要引号,file variable是列表中的文件名,variable file包含文件的内容。你知道吗
演示如下:
相关问题 更多 >
编程相关推荐