0

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: ')))
sushanth
  • 6,960
  • 3
  • 13
  • 23
Binh Nguyen
  • 29
  • 1
  • 4
  • 1
    To iterate over files in a dir https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory ; Also don't return huge lists, rather return them as generators; – Aditya Jun 21 '20 at 04:25
  • 1
    You can only return from a function once. – Karl Knechtel Jun 21 '20 at 04:48
  • Do you mean the line: for file in list_file_name(path) ? Actually I tried removing the function and add: for file in os.listdir(path) directly. But it still doesn't work. – Binh Nguyen Jun 21 '20 at 04:51

1 Answers1

1

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)))
    
MrNobody33
  • 6,003
  • 3
  • 17
  • 1
    Glad it helps you, I just edited to open the file correctly using `with`, please take note of that. Happy encoding!:) – MrNobody33 Jun 21 '20 at 04:51
  • What's the difference between with open as and the direct assignment? Actually I tried editing with open as and it does not show as expected. The 1st way is working. – Binh Nguyen Jun 21 '20 at 04:59
  • Basically "with" allows you to not forget to close the file you have opened, as an open/close encapsulated. See more differences in [link1](https://stackoverflow.com/questions/34429519/python-difference-between-open-and-with-open) and [link2](https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for). Hope it'll be clear. – MrNobody33 Jun 21 '20 at 05:05