如何在python中搜索文件中的字符串?

时间:2017-07-13 17:22:12

标签: python python-3.x

我在文件中搜索字符串,但即使文件中有匹配的字符串,它也总是返回false。我哪里错了?

file = open('temp.txt', 'r')

def search(userinput, file):

    file.seek(0)
    filecontent = file.readlines()
    for i in filecontent:
        sp = i.split(' ')
        t_name = sp[0] + ' ' + sp[1]
        print (t_name)
    if (t_name == userinput):
        return True
    else:
        return False


searchstr = 'Peter Piper'
found = search(searchstr, file)
print (found)
file.close

TEMP.TXT

Peter Piper 20 30
Tom Cat 10 20
Jerry Mouse 30 50

3 个答案:

答案 0 :(得分:1)

与您用来解释具体问题的代码示例保持同步...

您的问题是,您实际上只是在for循环运行后检查t_name是否为userinput。你想要做的就是这个

Peter Piper 20 30
Tom Cat 10 20
Jerry Mouse 30 50




file = open('temp.txt', 'r')

def search(userinput, file):

    file.seek(0)
    filecontent = file.readlines()
    for i in filecontent:
        sp = i.split(' ')
        t_name = sp[0] + ' ' + sp[1]
        print (t_name)
        if (t_name == userinput):
            return True
    return False


searchstr = 'Peter Piper'
found = search(searchstr, file)
print (found)
file.close

在我的代码示例中,每次for循环运行时,它都会检查名称是否匹配,如果是,则结束函数并返回True。如果它永远不会结束函数并在for循环结束之前返回True,则表示没有名称是匹配的,并且在for循环完成后它应该返回False

答案 1 :(得分:0)

你可以试试这个:

f = open('filename.txt').readlines()

f = [i.strip('\n') for i in f]

word = 'Peter Piper'
if any(word in i for i in f):
    print "word exists in file"

答案 2 :(得分:0)

问题是你正在检查外部循环t_nameJerry Mouse这是最后一个值,它应该是

file = open('temp.txt', 'r')

def search(userinput, file):
    file.seek(0)
    filecontent = file.readlines()
    for i in filecontent:
        sp = i.split(' ')
        #print(sp)
        t_name = sp[0] + ' ' + sp[1]
        print (t_name)
        if (t_name == userinput):
            return True
    return False


searchstr = 'Peter Piper'
found = search(searchstr, file)
print (found)
file.close