Chinese_Text_Classification.../export_all_pyfile.py
superlishunqin 07c7151272 2th-version
2025-03-13 09:35:44 +08:00

84 lines
2.5 KiB
Python

import os
def find_all_python_files(root_dir='.'):
"""
查找指定目录及其所有子目录下的所有Python文件
Args:
root_dir: 根目录路径,默认为当前目录
Returns:
包含所有Python文件路径的列表
"""
python_files = []
# 遍历根目录及所有子目录
for dirpath, dirnames, filenames in os.walk(root_dir):
# 查找所有.py文件
for filename in filenames:
if filename.endswith('.py'):
# 构建完整文件路径
full_path = os.path.join(dirpath, filename)
python_files.append(full_path)
return python_files
def export_file_contents_to_txt(python_files, output_file='python_contents.txt'):
"""
将所有Python文件的内容导出到一个TXT文件
Args:
python_files: Python文件路径列表
output_file: 输出TXT文件名
"""
with open(output_file, 'w', encoding='utf-8') as outfile:
for file_path in python_files:
# 获取相对路径以便更好地显示
rel_path = os.path.relpath(file_path)
# 写入文件分隔符
outfile.write(f"\n{'=' * 80}\n")
outfile.write(f"文件: {rel_path}\n")
outfile.write(f"{'=' * 80}\n\n")
# 读取Python文件内容并写入输出文件
try:
with open(file_path, 'r', encoding='utf-8') as infile:
content = infile.read()
outfile.write(content)
outfile.write("\n") # 文件末尾添加换行
except Exception as e:
outfile.write(f"[无法读取文件内容: {str(e)}]\n")
print(f"已将{len(python_files)}个Python文件的内容导出到 {output_file}")
def main():
# 获取当前工作目录
current_dir = os.getcwd()
print(f"正在搜索目录: {current_dir}")
# 查找所有Python文件
python_files = find_all_python_files(current_dir)
if python_files:
print(f"找到 {len(python_files)} 个Python文件")
# 导出所有文件内容到TXT
export_file_contents_to_txt(python_files)
# 打印处理的文件列表
for i, file_path in enumerate(python_files[:10]):
rel_path = os.path.relpath(file_path)
print(f"{i + 1}. {rel_path}")
if len(python_files) > 10:
print(f"... 还有 {len(python_files) - 10} 个文件")
else:
print("未找到任何Python文件")
if __name__ == "__main__":
main()