Will this code work?

I am not sure if this code will actually work, but if it does, how do I get it to print multiple file names if the word is found in them. Right now, my program will only print one file name if it has the word you are looking for.

import os

def search():
  word = input("What is the word you are looking for? ")
  file_names = []
  for x in os.listdir():
      if x.endswith(".txt"):
          file_names.append(x)
  for files in file_names:
    file_s = open(files, "r")
    read_file = file_s.read()
  if word in read_file: 
    print("The word", word, "was found in", files)
  else: 
    print("The word", word , "could not be found")
  file_s.close() 

search()

Should those lines be inside the for loop block?

Yes. Should they be outside of the loop?

From the way the code is indented, it looks to be outside. Might want to fix that.

Won’t the file(s) close either way?

One would expect that each file is opened and closed within the loop.

Hmm, I put that line inside the loop but, I still get the same output.

Please re-post your code (as a sample, not a codebyte) so we can get another look at it.

How would I do that? :sweat_smile:

Paste in your code, select it all, and click the </> button.

def search():

  word = input("What is the word you are looking for? ")

  file_names = []

  for x in os.listdir():

      if x.endswith(".txt"):

          file_names.append(x)

  for files in file_names:

    file_s = open(files, "r")

    read_file = file_s.read()

  if word in read_file: 

    print("The word", word, "was found in", files)

  else: 

    print("The word", word , "could not be found")

    file_s.close() 

search()

Your if statement is outside of the loop body.

That worked, thank you very much! I didn’t even know if the code before that would work in the first place because I just started not too long ago.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.