简体   繁体   English

Python-搜索字符串是否在文件中

[英]Python - searching if string is in file

I want to search for string in file and if there is string make action and if there isn´t string make other action, but from this code: 我想在文件中搜索字符串,如果有字符串make操作,如果没有字符串make其他操作,但是从以下代码中进行搜索:

    itcontains = self.textCtrl2.GetValue()
    self.textCtrl.AppendText("\nTY: " + itcontains)
    self.textCtrl2.Clear()
    pztxtflpath = "TCM/Zoznam.txt"
    linenr = 0
    with open(pztxtflpath) as f:
        found = False
        for line in f:
            if re.search("\b{0}\b".format(itcontains),line):
                hisanswpath = "TCM/" + itcontains + ".txt"
                hisansfl = codecs.open(hisanswpath, "r")
                textline = hisansfl.readline()
                linenr = 0
                ans = ""
                while textline <> "":
                    linenr += 1
                    textline = hisansfl.readline()
                hisansfl.close()
                rnd = random.randint(1, linenr) - 1
                hisansfl = codecs.open(pztxtflpath, "r")
                textline = hisansfl.readline()
                linenr = 0
                pzd = ""
                while linenr <> rnd:
                    textline = hisansfl.readline()
                    linenr += 1
                ans = textline
                hisansfl.close()
                self.textCtrl.AppendText("\nTexter: " + ans)
        if not found:
            self.textCtrl.AppendText("\nTexter: " + itcontains)
            wrtnw = codecs.open(pztxtflpath, "a")
            wrtnw.write("\n" + itcontains)
            wrtnw.close

If there is not that string it is working corectly, but if there is that string, what i am searching for it makes if not found action. 如果没有那个字符串,它就可以正常工作,但是,如果有那个字符串,我在搜索它的内容将导致找不到动作。 I really don´t know how to fix it, i have already try some codes from other sites, but in my code it doesn´t works. 我真的不知道如何解决它,我已经尝试过其他站点的一些代码,但是在我的代码中它不起作用。 Can somebody help please? 有人可以帮忙吗?

Are you saying that the code underneath the following if statement executes if the string contains what you're looking for? 您是说如果字符串包含您要查找的内容, 以下if语句下面的代码将执行?

 if re.search("\b{0}\b".format(itcontains),line):

If so, then you just need to add the following to the code block underneath this statement: 如果是这样,则只需要在此语句下面的代码块中添加以下内容:

found = True

This will keep your if not found clause from running. 这将使您的if if not found子句无法运行。 If the string you are looking for should only be found once, I would also add a break statement to your first statement to break out of the loop. 如果您要查找的字符串仅找到一次,我还将在第一条语句中添加一个break语句以退出循环。

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

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