在文件中搜索术语

时间:2018-03-01 10:42:52

标签: python file search

我的脚本出现问题。我想在搜索列表中定义的不同文件中找到一些术语。但是 - 它不会找到这些术语,即使它们肯定包含在这些文件中。我查了一下。

我错过了什么吗?

path = '/mypath'

for filename in glob.glob(os.path.join(path, '*.txt')):
    with open(filename) as infp:
        mylist = infp.read().splitlines() 
        for word in mylist:
            searchlist = ["term1", "term2", "term3"]
            for i in searchlist:
                if i in word:
                    print ('found')
                else: 
                    print ('not found')

1 个答案:

答案 0 :(得分:1)

这可能会有所帮助

path = '/mypath'

for filename in glob.glob(os.path.join(path, '*.txt')):
    with open(filename) as infp:
        data = infp.read()    #Just Read the content
        searchlist = ["term1", "term2", "term3"]
        for i in searchlist:
            if i in data:  #Check if search term in content. 
                print('found')
            else: 
                print('not found')