0

I have a huge dir, with sub dirs and txt files. I would like to search my dir/s recursevly for a specific string. I would like to print the full path, and keyword if i find a match. For some reason I can't seem to get if keyword in line to work. (I know that "williams" is in my files)

import os
search_path = "/home/lasse/Desktop/DB1"
file_type = ".txt"
keyword = "williams"

if not (search_path.endswith("/") or search_path.endswith("\\")):
    search_path = search_path + "/"

if not os.path.exists(search_path):
    search_path = "." 
    print("Path dosn't exists") 

for folder, dirs, files in os.walk(search_path):
    for file in files:
        if file.endswith(file_type):
            fullpath = os.path.join(folder, file)

            with open(fullpath, 'r') as my_file:
                for line in my_file:
                    print("test")
                    if keyword in line:
                        print(fullpath, line, keyword)
                    else:
                    print("Cant find keyword keyword")
Georgy
  • 12,464
  • 7
  • 65
  • 73
  • Have you tried to `print(fullpath)` to ensure you're actually getting to the file you know has the keyword in it? And are you sure "williams" is the right keyword instead of "Williams"? Also, check out https://stackoverflow.com/a/4944929/1451664 – Chris Jan 28 '19 at 12:27
  • i can print the line where it says print("test").. my code never enters the if statement - just skips to the else... also i need the search to be recursive for all files in dirs and sub dirs.. most exampels are only searching one file.. – Lasse Bøg Jan 28 '19 at 12:50
  • That `print` will execute for *every* line of *every* file. First indent the print statement under the `else`. Also, create a test with a single file you know contains the keyword to help isolate the problem. Right now it could be that you never actually enumerate a path that contains the keyword or there's a mistake in the keyword itself (lowercase vs uppercase, unicode characters, etc.). – Chris Jan 28 '19 at 13:06
  • Thx chris.. i got it under control now :) – Lasse Bøg Jan 29 '19 at 14:05

0 Answers0