-1

I have an application which is about word manipulation, and I want to use it in order to look through a list of .txt files inside a subfolder(in this case is Used Words), and within each file, I need to look for a specific word. If I find that word, I want to get an error message indicating the word has already been used by the application before.

def buildShow():
    directory = "Used Words"
    if(os.path.exists(directory)):
        for files in os.walk(directory):
            for file in files:
                if file.endswith(".txt"):
                    tk.messagebox.showinfo("Warning", "World Already Used")
Sajan
  • 1,247
  • 1
  • 5
  • 13
Chris
  • 37
  • 7
  • 1
    You have walked through the directory to find files and you have iterated for each file containing .txt, but you have not read them to do something? – coldy Apr 03 '20 at 17:41
  • Does this answer your question? [Does Python have a string 'contains' substring method?](https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method) – SuperStormer Apr 03 '20 at 17:46

1 Answers1

0

Open each file inside your inner-most loop and check if your desired word exists using the following code.

file=open(os.path.join(directory,file),"r+")
txt=file.read()
file.close()
lines=txt.split('\n') #all lines in a file
words=[]
for line in lines:
    words.append(line.split('\n'))
if "<your word>" in words: #words list contain all words in the file
    tk.messagebox.showinfo("Warning", "World Already Used")
Hamza Khurshid
  • 765
  • 7
  • 18
  • The read() will read the entire content as a string, so for example, if the search for word is `a`, then it the if will be true even if there is `an` and not `a`. So, one will need to add that content into list by a delimiter like `" "` and then find the required word. – coldy Apr 03 '20 at 17:39
  • I get the following error when I click the button needed: File "C:\Users\Christian\Google Drive\Safe\Ali\Ali\BuildGameList.py", line 182, in buildShow if (file.endswith(".txt")): AttributeError: 'list' object has no attribute 'endswith' – Chris Apr 03 '20 at 17:48