与 AI 聊天更顺畅:cat_code.py
为什么需要这个脚本?
想象一下,你正在和 AI 讨论一个 bug,AI 说:“能让我看看你的代码吗?”你的项目里有几十个文件,散落在不同目录,手动整理太费劲。更别提有些文件你压根不想分享(比如 .git
或 venv
)。这时候,你需要一个工具,能一键把项目文件整理好,生成一个清晰的“全景图”,方便复制粘贴给 AI。这就是这个脚本的使命!
它是怎么工作的?
这个脚本用 Python 编写,简单易用。它会:
- 遍历项目目录:扫描当前目录及其子目录,找到所有文件和文件夹。
- 智能过滤:跳过不需要的内容,比如
.git
、.idea
等。 - 集中输出:把所有文件路径和内容整理到一个
my_files.txt
文件中,同时在控制台打印,方便你检查。 - 人性化处理:
- 文本文件:读取并输出内容。
- 空文件:提示“此文件为空”。
- 二进制文件:提示“无法读取,可能是二进制文件”。
- 目录:显示是否为空。
运行一次脚本,你就得到了一个包含项目所有关键信息的文本文件,随时可以丢给 AI,交流起来轻松又高效!
代码展示
下面是完整的脚本代码,逻辑清晰,注释详细,拿来就能用:
import os
from pathlib import Path# 目的:为了与 AI 交流更方便,
# 将项目中所有代码和文件内容输出到一个地方,集中管理。def list_and_print_files():# 获取当前目录current_dir = Path.cwd()# 要排除的文件和目录列表exclude_items = [".git", ".idea", "__pycache__",".gitignore", "venv", ".env", "read_venv", "total_json_data","gg.bat","my_files.txt", "cat_code.py","过程记录.md", "README.md", "readme.md", "gist_venv"]# 输出文件output_file = "my_files.txt"# 打开输出文件以写入结果with open(output_file, 'w', encoding='utf-8') as out_f:# 遍历当前目录for root, dirs, files in os.walk(current_dir, topdown=True):# 排除指定的目录dirs[:] = [d for d in dirs if d not in exclude_items]# 排除指定的文件files[:] = [f for f in files if f not in exclude_items]# 处理当前目录中的每个文件for name in files:file_path = Path(root) / name# 获取相对路径以便输出更简洁relative_path = file_path.relative_to(current_dir)# 格式化输出output = f"\n文件: {relative_path}\n"print(output.strip()) # 打印到控制台out_f.write(output) # 写入文件# 检查文件是否为空if file_path.stat().st_size == 0:output = "内容: 此文件为空\n"print(output.strip())out_f.write(output)continuetry:# 尝试以文本形式读取文件with open(file_path, 'r', encoding='utf-8') as f:content = f.read()if content.strip() == "":output = "内容: 此文件为空\n"else:output = f"内容:\n{content}\n"print(output.strip()) # 打印到控制台out_f.write(output) # 写入文件except UnicodeDecodeError:output = "内容: [无法作为文本读取,可能是二进制文件]\n"print(output.strip())out_f.write(output)except PermissionError:output = "内容: [权限被拒绝]\n"print(output.strip())out_f.write(output)except Exception as e:output = f"内容: [读取文件出错: {e}]\n"print(output.strip())out_f.write(output)# 处理当前目录中的每个子目录for name in dirs:dir_path = Path(root) / name# 获取相对路径relative_path = dir_path.relative_to(current_dir)# 格式化输出output = f"\n目录: {relative_path}\n"print(output.strip()) # 打印到控制台out_f.write(output) # 写入文件# 检查目录是否为空is_empty = Truefor _ in dir_path.iterdir():is_empty = Falsebreakif is_empty:output = "内容: 此目录为空\n"else:output = "内容: [这是一个目录]\n"print(output.strip()) # 打印到控制台out_f.write(output) # 写入文件if __name__ == "__main__":list_and_print_files()
如何使用?
- 放入项目:把脚本保存为
cat_code.py
,放到你的项目根目录。 - 运行脚本:在终端输入
python cat_code.py
。 - 查看结果:打开生成的
my_files.txt
,里面就是你项目的全部文件内容。 - 分享给 AI:直接复制
my_files.txt
的内容,或者把文件发给 AI。
为什么它让与 AI 聊天更方便?
- 省时:不用手动找文件、复制粘贴,一次性搞定。
- 完整:AI 能看到项目的全貌,分析问题更准确。
- 灵活:想排除某些文件?改改
exclude_items
列表就行。 - 清晰:相对路径和内容分隔明确,AI 读起来不费劲。
试试看吧!
下次和 AI 聊天时,别再手忙脚乱了。跑一下这个脚本,把 my_files.txt
丢过去,轻松开启高效交流模式。AI 可能会夸你:“哇,你的代码整理得真好!”快试试吧,让你的项目文件成为 AI 眼中的“明星”!