70 lines
1.8 KiB
Python
70 lines
1.8 KiB
Python
import os
|
|
from docx import Document
|
|
|
|
|
|
def find_files(start_path, extensions):
|
|
"""
|
|
遍历目录并找到指定扩展名的文件。
|
|
|
|
:param start_path: 起始路径
|
|
:param extensions: 需要查找的文件扩展名列表
|
|
:return: 文件路径列表
|
|
"""
|
|
file_list = []
|
|
for root, dirs, files in os.walk(start_path):
|
|
for file in files:
|
|
if any(file.endswith(ext) for ext in extensions):
|
|
file_list.append(os.path.join(root, file))
|
|
return file_list
|
|
|
|
|
|
def read_files(file_list):
|
|
"""
|
|
读取文件内容。
|
|
|
|
:param file_list: 文件路径列表
|
|
:return: 文件内容字典
|
|
"""
|
|
content_dict = {}
|
|
for file_path in file_list:
|
|
with open(file_path, 'r', encoding='utf-8') as file:
|
|
content_dict[file_path] = file.read()
|
|
return content_dict
|
|
|
|
|
|
def save_to_docx(content_dict, output_file):
|
|
"""
|
|
将文件内容字典保存到 DOCX 文件。
|
|
|
|
:param content_dict: 文件内容字典
|
|
:param output_file: 输出的 DOCX 文件名
|
|
"""
|
|
doc = Document()
|
|
for file_path, content in content_dict.items():
|
|
doc.add_heading(file_path, level=1)
|
|
doc.add_paragraph(content)
|
|
doc.add_page_break() # 添加分页符
|
|
doc.save(output_file)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# 需要遍历的目录
|
|
directory = '/Users/lishunqin/Desktop/study/pychram project/AWS-sure'
|
|
|
|
# 需要查找的文件扩展名
|
|
extensions = ['.py', '.html', '.env', '.css', 'js']
|
|
|
|
# 查找文件
|
|
files = find_files(directory, extensions)
|
|
|
|
# 读取文件内容
|
|
content_dict = read_files(files)
|
|
|
|
# 输出 DOCX 文件名
|
|
output_docx = 'output_files_content.docx'
|
|
|
|
# 保存到 DOCX 文件
|
|
save_to_docx(content_dict, output_docx)
|
|
|
|
print(f"找到 {len(files)} 个文件,并保存了内容到 {output_docx}")
|