I need help writing a light weight Python (v3.6.4) script to search for a single keyword within a directory of files and folders. Currently, I am using Notepad++ to search the directory of files, although I believe a Python script would be quicker?
Current script:
import os
key = input("Search For?: ")
folder = os.listdir("/")
for line in folder:if key in line:print(line)
EDIT: I am using Notepad++ to run these search queries.
The directory which I would like to search through has multiple levels of files within folders.
You should really use grep
(i.e. grep -Ril "keyword" /
) or, if on Windows, findstr
(findstr /I /M /C:"keyword" /S \*
) but if you insist on doing it through Python you'll want to use os.walk()
to walk through the root directory recursively, then open each found file and iterate over it to find if it contains your desired keyword, something like:
import oskeyword = input("Search For?: ") # ask the user for keyword, use raw_input() on Python 2.xroot_dir = "/" # path to the root directory to search
for root, dirs, files in os.walk(root_dir, onerror=None): # walk the root dirfor filename in files: # iterate over the files in the current dirfile_path = os.path.join(root, filename) # build the file pathtry:with open(file_path, "rb") as f: # open the file for reading# read the file line by linefor line in f: # use: for i, line in enumerate(f) if you need line numberstry:line = line.decode("utf-8") # try to decode the contents to utf-8except ValueError: # decoding failed, skip the linecontinueif keyword in line: # if the keyword exists on the current line...print(file_path) # print the file pathbreak # no need to iterate over the rest of the fileexcept (IOError, OSError): # ignore read and permission errorspass
TEST: I've just tested it searching for PyEnum_Type
through CPython source code cloned to F:\.tmp\cpython-master
(thus root_dir = r"F:\.tmp\cpython-master"
) on my local system running CPython 3.5.1 and the results are as expected:
Search For?: PyEnum_Type
F:\.tmp\cpython-master\Include\enumobject.h
F:\.tmp\cpython-master\Objects\enumobject.c
F:\.tmp\cpython-master\Objects\object.c
F:\.tmp\cpython-master\PC\python3.def
F:\.tmp\cpython-master\Python\bltinmodule.c
If it doesn't produce any results you're most likely setting your path wrong or you're searching for something that doesn't exist in the files under the defined root_dir
(or your user doesn't have access to them).