简体   繁体   中英

Loop over file names in a folder and return file name if a key word is in the file

I'm coding for this simple requirements: Search for a key word and return the file name that has such key word

This is the first part of the code to search for 'txt' files. But I'm having problem with looping over file names: code just shows 1 result (file) while it is expected to list all file names.

import os

#list file names 
def list_file_name(path):
    fileList = os.listdir(path)
    return(fileList)

#Function 1: search key_word in txt file
def search_txt(path, keyWord):
    for file in list_file_name(path):
        if file.endswith('txt'):
            f = open(path + '/' + file, 'r')
            openFile = f.read()
            if keyWord in openFile:
                return('Key word {} is in {}'.format(keyWord, file))
            else:
                return('No key word found')
        continue

#run the function
print(search_txt(input('Please input folder path: '), input('Please input key word: ')))

You could try with this, by creating a list of files that have the key:

def search_txt(path, keyWord):
    lsfiles=[]
    for file in list_file_name(path):
        if file.endswith('txt'):
            with open(path + '/' + file, 'r') as f:
                openFile = f.read()
                if keyWord in openFile:
                    lsfiles.append(file)
    if len(lsfiles)==0:
        return('No key word found ')
    else:
        return('Key word {} is in {}'.format(keyWord, ', '.join(lsfiles)))
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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