我想在文件中搜索字符串,如果有字符串,则执行操作,如果没有字符串,则执行其他操作,但根据以下代码:
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语句下面的代码吗?你知道吗
如果是这样,则只需将以下内容添加到此语句下面的代码块中:
这将阻止if not found子句运行。如果您要查找的字符串只应找到一次,我还将在第一个语句中添加一个break语句以跳出循环。你知道吗
相关问题 更多 >
编程相关推荐