Appearance
How to search for a string in text files?
Here's a Python code snippet that demonstrates how to search for a string in all text files in a directory:
Search for a string in all text files in a directory
python
import os
def search_string(directory, search_string):
for root, dirs, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
with open(file_path, "r") as f:
content = f.read()
if search_string in content:
print(f"Found '{search_string}' in {file_path}")
search_string("/path/to/directory", "search string")
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
This code recursively walks through all subdirectories in the specified directory, opens each file, reads its contents, and checks if the search string is present in the file's contents. If the search string is found, it prints the file's path. You can also use the 'glob' library to search specific file extension
Use the 'glob' library to search specific file extension
python
import glob
def search_string(directory, search_string,extension):
for file in glob.glob(f'{directory}/*.{extension}'):
with open(file, "r") as f:
content = f.read()
if search_string in content:
print(f"Found '{search_string}' in {file}")
search_string("/path/to/directory", "search string",'txt')Note that this code snippet assumes that the text files are encoded in UTF-8 or a similar encoding that supports the characters in the search string. If the text files use a different encoding, you may need to specify the encoding when opening the files (e.g., open(file_path, "r", encoding="iso-8859-1")).