qbiocode.utils.find_string module#

String search utilities for finding specific content across multiple files.

This module provides functions to search for strings or patterns in files within a directory, useful for auditing configurations, finding specific parameters, or validating file contents.

Summary#

Functions:

find_string_in_files

Search for a specific string in all files within a directory.

Reference#

find_string_in_files(directory, search_string, file_pattern=None, case_sensitive=True, return_lines=False, verbose=True)[source]#

Search for a specific string in all files within a directory.

Scans files in the specified directory and identifies which files contain the search string. Optionally returns the matching lines with line numbers. Useful for auditing configurations, finding specific parameters, or validating settings across multiple files.

Parameters:
  • directory (str) – Path to the directory containing files to search.

  • search_string (str) – The string to search for in the files.

  • file_pattern (str, optional) – File extension or pattern to filter (e.g., ‘.yaml’, ‘.csv’, ‘.txt’). If None, all files are searched. Default is None.

  • case_sensitive (bool, optional) – If True, search is case-sensitive. Default is True.

  • return_lines (bool, optional) – If True, return matching lines with line numbers. Default is False.

  • verbose (bool, optional) – If True, print progress and results. Default is True.

Returns:

Dictionary mapping file paths to list of (line_number, line_content) tuples for files containing the search string. If return_lines is False, the list contains empty tuples.

Return type:

Dict[str, List[Tuple[int, str]]]

Raises:
  • FileNotFoundError – If the specified directory does not exist.

  • NotADirectoryError – If the specified path is not a directory.

Examples

Basic search for a string:

>>> results = find_string_in_files(
...     'configs/',
...     'embeddings: none'
... )
>>> print(f"Found in {len(results)} files")

Search with line numbers returned:

>>> results = find_string_in_files(
...     'configs/qml_gridsearch/',
...     'n_qubits: 4',
...     file_pattern='.yaml',
...     return_lines=True
... )
>>> for filepath, matches in results.items():
...     print(f"{filepath}:")
...     for line_num, line_content in matches:
...         print(f"  Line {line_num}: {line_content.strip()}")

Case-insensitive search:

>>> results = find_string_in_files(
...     'logs/',
...     'error',
...     file_pattern='.log',
...     case_sensitive=False
... )

Integration with QProfiler workflow:

>>> # Find all configs using a specific embedding
>>> config_dir = "configs/experiments/"
>>> results = find_string_in_files(
...     config_dir,
...     'embeddings: pca',
...     file_pattern='.yaml',
...     verbose=True
... )
>>>
>>> if results:
...     print(f"Found {len(results)} configs using PCA embedding")
...     for config_file in results.keys():
...         print(f"  - {os.path.basename(config_file)}")

Notes

  • Only text files are supported; binary files will be skipped

  • Large files may consume significant memory if return_lines=True

  • Symbolic links are followed and treated as regular files

  • Hidden files (starting with ‘.’) are included in search

See also

find_duplicate_files

Find files with identical content

checkpoint_restart

Resume interrupted batch processing jobs