【问题标题】:How do i have python3 search for a specific string in a text file我如何让python3在文本文件中搜索特定字符串
【发布时间】:2018-01-06 19:25:41
【问题描述】:

我要做的就是让程序查找特定的字符串,如果文件包含该字符串,则添加到变量中,如果不只是打印它不起作用。但是它一直说当我知道它在文件中时找不到该字符串。

for line in open("/home/cp/Desktop/config"):
    if "PermitRootLogin no" in line:
        num_of_points1 = num_of_points1 + 4
        num_of_vulns1 = num_of_vulns1 + 1
    else:
        print('sshd_config is still vulnerable')
        break

这是它读取的文件

This should work
Possibly
PermitRootLogin no
hmmmmmmmmmm
aaa

我想要它做的是在文件中找到“PermitRootLogin no”,但它只是一直表现得好像从未找到该字符串。并打印 else 语句。当我在寻找教程时,他们都在尝试做其他事情,所以我愿意接受任何建议。谢谢你,我只是真的卡住了。

【问题讨论】:

    标签: linux string python-3.x parsing if-statement


    【解决方案1】:

    嗨,你的问题是你 else 之后的休息。 您的代码读取第一行并打印出第一行不是您搜索的字符串。 下面的代码对我有用。 希望这会有所帮助。

    found = False
    
    for line in open('config'):
        if "PermitRootLogin no" in line:
            num_of_points1 = num_of_points1 + 4
            num_of_vulns1 = num_of_vulns1 + 1
            found = True
    if not found:
        print('sshd_config is still vulnerable')
    

    【讨论】:

    • 好的,非常感谢,所以如果我有break stamen t,它只会搜索第一行?
    • @lavarockman break 命令中断循环。如果您的 else 语句会在例如第三行,则只搜索三行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 2012-09-28
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多