繁体   English   中英

在文件python中使用通配符搜索字符串

[英]Search for string with wildcard in file python

基本上,我想做的是检查文件(File1)与另一个文件(template.file)缺少哪些字符串。 一旦有了这个,我将在File1后面附加缺少的字符串。

File1内容:

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"

问题是,在我的示例中,该脚本仅会打印为dn_name找到的脚本,而不会打印为ip_addr找到的脚本,因为它也具有IP。 我基本上需要这样的东西

if line* in t:

我怎样才能做到这一点?

您忘记了换行符,特别是在模板文件中搜索ip_addr:\\n ,该文件不在其中(因为程序正确地告诉了您)。 因此,要实现您想要的目标,您必须使用rstrip()将换行符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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM