美文网首页
py导代码到word

py导代码到word

作者: 耗子_aca3 | 来源:发表于2021-06-30 14:26 被阅读0次

鉴于网上水帖太多,自己正好要弄个软著的代码导出到word,东拼西凑一个可用版

import os
from docx import Document # 没有包的话引一下 pip3 install python-docx  

def show_files(path, all_files):
    # 首先遍历当前目录所有文件及文件夹
    file_list = os.listdir(path)
    # 准备循环判断每个元素是否是文件夹还是文件,是文件的话,把名称传入list,是文件夹的话,递归
    for file in file_list:
        # 利用os.path.join()方法取得路径全名,并存入cur_path变量,否则每次只能遍历一层目录
        cur_path = os.path.join(path, file)
        # 判断是否是文件夹
        if os.path.isdir(cur_path):
            show_files(cur_path, all_files)
        else:
            if '.go' in file:
                all_files.append(os.path.join(path, file)) # 这里根据自己需求,看看要啥类型的文件

    return all_files


# 传入空的list接收文件名
all_files_path = show_files("D:\\Code\\src\\live-broadcast", []) # 从哪个文件夹查找所有文档出来,文档类型看上面的注释
# 循环打印show_files函数返回的文件名列表
for file_path in all_files_path:
    docx_path = 'D:\\Code\\src\\live-broadcast\\tar.docx' # 需要导入到哪个目标word文件
    doc = Document(docx_path)
    # with open(file_path, 'r', encoding='UTF-8') as file_obj: # 注释这三行是按行为段落,看起来会挺多空行
    #     for row in file_obj:
    #         doc.add_paragraph(row)
    with open(file_path, 'r', encoding='UTF-8') as file_obj:
        doc.add_paragraph(file_obj.read())
    doc.add_paragraph('\n')
    doc.save(docx_path)

相关文章

网友评论

      本文标题:py导代码到word

      本文链接:https://www.haomeiwen.com/subject/yhdrultx.html