Skip to content

Instantly share code, notes, and snippets.

@talentestors
Created April 27, 2025 15:37
Show Gist options
  • Select an option

  • Save talentestors/9e7ad8dae66a857f45f05272a9168e3d to your computer and use it in GitHub Desktop.

Select an option

Save talentestors/9e7ad8dae66a857f45f05272a9168e3d to your computer and use it in GitHub Desktop.
Search for text within a file, starting from the current file directory. `python test.py --search word` || `python test.py -s word`
import os
import argparse
def search_text_in_files(search_term, start_dir):
"""
递归检索目录中的文本文件,查找特定文本内容。
:param search_term: 要查找的文本内容
:param start_dir: 开始搜索的目录
"""
# 支持的文本文件扩展名
text_extensions = ('.txt', '.md', '.py', '.java', '.c', '.cpp', '.js', '.html', '.css')
# 遍历目录
for root, dirs, files in os.walk(start_dir):
for file in files:
# 检查文件是否为文本文件(根据扩展名)
if file.endswith(text_extensions):
file_path = os.path.join(root, file)
try:
# 读取文件内容
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
for line_num, line in enumerate(lines, 1):
if search_term in line:
print(f"找到 '{search_term}' 在文件: {file_path}")
print(f"行号: {line_num}")
print(f"内容: {line.strip()}")
print("-" * 50)
except UnicodeDecodeError:
print(f"无法以 UTF-8 编码读取文件: {file_path},已跳过。")
except Exception as e:
print(f"读取文件 {file_path} 时发生错误: {e}")
if __name__ == "__main__":
# 解析命令行参数
parser = argparse.ArgumentParser(description='查找文件中的特定文本。')
parser.add_argument('-s', '--search', help='要搜索的关键词', required=True)
args = parser.parse_args()
# 搜索关键词
search_term = args.search
# 获取当前脚本的目录作为起点
current_dir = os.path.dirname(os.path.abspath(__file__))
print(f"开始从目录 {current_dir} 搜索 '{search_term}'...\n")
# 执行搜索
search_text_in_files(search_term, current_dir)
print("搜索完成。")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment