File size: 2,707 Bytes
12e1035
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e3d91216-d411-4039-a914-3d5e23cb5335",
   "metadata": {
    "ExecutionIndicator": {
     "show": true
    },
    "execution": {
     "iopub.execute_input": "2024-08-16T09:45:06.206727Z",
     "iopub.status.busy": "2024-08-16T09:45:06.206308Z",
     "iopub.status.idle": "2024-08-16T09:45:06.266958Z",
     "shell.execute_reply": "2024-08-16T09:45:06.266529Z",
     "shell.execute_reply.started": "2024-08-16T09:45:06.206705Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['/mnt/workspace/stable-diffusion-webui/modules/ui_postprocessing.py', '/mnt/workspace/stable-diffusion-webui/modules/.ipynb_checkpoints/ui_postprocessing-checkpoint.py']\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "def find_files_with_string(directory, search_string, file_extension=None):\n",
    "    matching_files = []\n",
    "    # 遍历目录下的所有文件和子目录\n",
    "    for root, dirs, files in os.walk(directory):\n",
    "        for file in files:\n",
    "            # 如果指定了文件格式,检查文件是否匹配\n",
    "            if file_extension and not file.endswith(file_extension):\n",
    "                continue\n",
    "            \n",
    "            file_path = os.path.join(root, file)\n",
    "            # 逐个文件打开并检查是否包含特定字符\n",
    "            try:\n",
    "                with open(file_path, 'r', encoding='utf-8') as f:\n",
    "                    if search_string in f.read():\n",
    "                        matching_files.append(file_path)\n",
    "            except (UnicodeDecodeError, FileNotFoundError):\n",
    "                # 如果文件不能被读取或者文件不存在,跳过\n",
    "                continue\n",
    "    return matching_files\n",
    "\n",
    "# 示例用法\n",
    "directory = '/mnt/workspace/stable-diffusion-webui'\n",
    "search_string = 'Batch from Directory'\n",
    "file_extension = '.py'  # 仅搜索特定格式的文件\n",
    "matching_files = find_files_with_string(directory, search_string, file_extension)\n",
    "print(matching_files)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}