find a string in all the files within a directory in python

You can find a string in all the files within a directory in Python by traversing through all the files in that directory and searching for the string in each file. Here's the sample code for doing this:

main.py
import os

# Define the directory path and the search string
dir_path = '/path/to/directory'
search_str = 'search_string'

# Traverse through all the files in the directory
for root, dirs, files in os.walk(dir_path):
    for file in files:
        file_path = os.path.join(root, file)
        
        # Open the file and read the content
        with open(file_path, 'r') as f:
            content = f.read()
            
        # Search for the string in the content
        if search_str in content:
            print(f"String found in file: {file_path}")
560 chars
19 lines

In this code, we first define the directory path and the search string. Then we traverse through all the files in the directory using os.walk() function. For each file, we open it, read its content, and search for the string using the in operator. If the string is found in the file, we print the file path to the console.

gistlibby LogSnag