在文件 python 中搜索带通配符的字符串
Search for string with wildcard in file python
基本上我要做的是检查文件 (File1) 在与另一个文件 (template.file) 比较时缺少哪些字符串。一旦我有了这个,我将在 File1 中附加缺少的字符串。
文件1内容:
dn_name:
ip_addr: 10.0.0.0
template.file内容:
dn_name:
ip_addr:
我的做法:
f = open("template.file", "r")
t = open("File1").read()
for line in f:
if line in t:
print "found" + 'line'
else:
print "Not found"
这个问题是,在我的示例中,脚本将只打印 found for dn_name: 但不会打印 ip_addr: 因为它也有 IP。
我基本上需要
if line* in t:
我该怎么做?
您忘记了换行符,特别是您在模板文件中搜索 ip_addr:\n
,但模板文件中不存在(正如程序正确告诉您的那样)。因此,要实现您想要的效果,您必须使用 rstrip()
将换行符去掉,如下所示:
f = open("template.file", "r")
t = open("File1").read()
for line in f:
if line.rstrip() in t:
print "found " + line
else:
print line + " Not found"
此外,python中没有*
,in
运算符已经完全按照你的要求做了。
最后,如果您想进行大量比较,那么我建议使用 set
。
基本上我要做的是检查文件 (File1) 在与另一个文件 (template.file) 比较时缺少哪些字符串。一旦我有了这个,我将在 File1 中附加缺少的字符串。
文件1内容:
dn_name:
ip_addr: 10.0.0.0
template.file内容:
dn_name:
ip_addr:
我的做法:
f = open("template.file", "r")
t = open("File1").read()
for line in f:
if line in t:
print "found" + 'line'
else:
print "Not found"
这个问题是,在我的示例中,脚本将只打印 found for dn_name: 但不会打印 ip_addr: 因为它也有 IP。 我基本上需要
if line* in t:
我该怎么做?
您忘记了换行符,特别是您在模板文件中搜索 ip_addr:\n
,但模板文件中不存在(正如程序正确告诉您的那样)。因此,要实现您想要的效果,您必须使用 rstrip()
将换行符去掉,如下所示:
f = open("template.file", "r")
t = open("File1").read()
for line in f:
if line.rstrip() in t:
print "found " + line
else:
print line + " Not found"
此外,python中没有*
,in
运算符已经完全按照你的要求做了。
最后,如果您想进行大量比较,那么我建议使用 set
。