【问题标题】:Search for string with wildcard in file python在文件python中搜索带通配符的字符串
【发布时间】:2016-02-09 09:50:25
【问题描述】:

基本上我要做的是检查一个文件(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"

这个问题是,在我的示例中,脚本只会打印找到 dn_name: 但不会打印 ip_addr: 因为它也有 IP。 我基本上需要像

if line* in t:

我该怎么做?

【问题讨论】:

  • 您要求您的程序在仅包含 ip_addr: 的文件中查找 ip_addr: 10.0.0.1。因此,它没有找到它。也许您打算在代码中交换 ft,或者您想要双向匹配?
  • 无论我从您的描述中得到什么,都比较键而不是行,例如使用 : 分割行,比较键并在缺少任何键时追加
  • @BasJansen 我的文件内容有误。
  • @BasJansen no ,我的错误出现在我上面的问题中。现在看看我的问题,你会看到我交换了 ip addr 10.0.0.0 的位置,但我仍然遇到同样的问题

标签: python string wildcard


【解决方案1】:

您忘记了换行符,特别是您在模板文件中搜索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

【讨论】:

    猜你喜欢
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-15
    • 2012-08-24
    相关资源
    最近更新 更多