gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
Python如何递归地遍历一个目录及其所有子目录下的py文件,然后import,对其中一个叫data的字典进行遍历,查找其是否含有某个字符串
- User
Python如何递归地遍历一个目录及其所有子目录下的py文件,然后import,对其中一个叫data的字典进行遍历,查找其是否含有某个字符串
- Assistant
要实现这个功能,您可以参考以下代码:
首先,使用
os.walk遍历目录及其子目录的所有文件,并检查文件是否以.py结尾。然后,使用importlib库导入模块,获取模块内名为data的字典。最后,遍历字典查找是否包含某个字符串。以下是示例代码:
import os import importlib import sys from pathlib import Path def search_data(module, target_str): if hasattr(module, 'data'): data_dict = module.data if isinstance(data_dict, dict): for key, value in data_dict.items(): if target_str in key or target_str in str(value): print(f"Found '{target_str}' in module {module.__name__} - key: {key}, value: {value}") def import_and_search(path, target_str): sys.path.insert(0, str(path.parent)) # 添加父目录到系统路径,以便能够正确地导入模块 try: module_name = str(path.stem) module = importlib.import_module(module_name) search_data(module, target_str) except Exception as e: print(f"Error importing module from {path}: {e}") finally: # 删除添加到系统路径的目录,避免可能的冲突 sys.path.pop(0) def main(search_directory, target_str): for root, dirs, files in os.walk(search_directory): for file in files: if file.endswith(".py"): file_path = Path(root) / file import_and_search(file_path, target_str) if __name__ == "__main__": search_directory = "path/to/search/directory" target_str = "search_keyword" main(search_directory, target_str)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.