Is there a way to search all available files in python?

I have this code that allows me to search the file test.txt for a word, but is there a way to search all available files for a word. I can’t find the answer on the web either :frowning: The part of my code is below.

def search():
  word = input("What is the word you are looking for? ")
  file1 = open("test.txt", "r")
  readfile = file1.read()
  if word in readfile: 
    print("The word", word, "was found in file")
  else: 
    print("The word", word , "could not be found")
  file1.close() 

By ‘all available files’ do you mean within a given directory dedicated to the program?

One could create file of just the names of the files that would apply to your program. Open that file and traverse the list, opening each file in turn, and searching through that.

1 Like

Yes, I meant all the files given in a directory. I did think about your suggestion but wanted to make sure that there was no easier way. Thanks for the help!

2 Likes

In expansion to @mtf’s point if you’re looking for a more generic solution where you might not know the underlying directory structure, various modules (this is by no means an exhaustive list) like os, glob and pathlib have tools for interacting with the operating system and could provide you with a list of filenames through which to perform your search.

2 Likes