Search for string within files of a directory

2024/10/5 14:55:21

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.

Answer

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).

https://en.xdnf.cn/q/120498.html

Related Q&A

Extract parent and child node from python tree

I am using nltks Tree data structure.Below is the sample nltk.Tree.(S(S(ADVP (RB recently))(NP (NN someone))(VP(VBD mentioned)(NP (DT the) (NN word) (NN malaria))(PP (TO to) (NP (PRP me)))))(, ,)(CC an…

Click button with selenium and python

Im trying to do web scraping with python on and Im having trouble clicking buttons. Ive tried 3 different youtube videos using Xpath, driver.find_element_by_link_text, and driver.find_element. What am …

Combinations of DataFrames from list

I have this:dfs_in_list = [df1, df2, df3, df4, df5]I want to concatenate all combinations of them one after the other (in a loop), like:pd.concat([df1, df2], axis=1) pd.concat([df1, df3], axis=1) p…

Python: iterate through dictionary and create list with results

I would like to iterate through a dictionary in Python in the form of:dictionary = {company: {0: apple,1: berry,2: pear},country: {0:GB,1:US,2:US} }To grab for example: every [company, country] if coun…

Jira Python: Syntax error appears when trying to print

from jira.client import jiraoptions = {server: https://URL.com} jira = JIRA(options, basic_auth=(username, password))issues = jira.search_issues(jqlquery) for issue in issues:print issueI want to print…

Matplotlib plt.xlim([x_min,x_max]), list object not callable

I want to plot a scatterplot, but set the x-label limits.axScatter = plt.subplot(111) axScatter.scatter(x=mean_var_r["Variance"],y=mean_var_r["Mean"]) xlim = [-0.003, 0.003] plt.xli…

Map column birthdates in python pandas df to astrology signs

I have a dataframe with a column that includes individuals birthdays. I would like to map that column to the individuals astrology sign using code I found (below). I am having trouble writing the code …

How to use python pandas to find a specific string in various rows

I am trying to do my taxes. I have over 2,000 rows of data in a CSV of orders. I am trying to just count and print the rows that contain "CA" so I know the ones I need to pay sales tax on. I …

How to cast a list to a dictionary

I have a list as a input made from tuples where the origin is the 1st object and the neighbour is the 2nd object of the tuple. for example :inp : lst = [(a,b),(b,a),(c,),(a,c)] out : {a: (a, [b, c]), …

Couldnt get rid of (_tkinter.TclError: bad event type or keysym UP) problem

I am running a Linux mint for the first time . I tried coding a python problem but for two days I am continiously facing problems due to Linux interface please This is my code:-import turtleimport time…