本文主要是介绍python实现txtSaveAsWord txt文件另存为word,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
# word_1.py
# 导入库
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qnimport re
import os#这个函数用来搜索指定搜索路径中的‘.txt’作为后缀的文件,传入参数是要搜索的路径,返回值的列表中,存放的是生成的绝对路径的名称。
def search_txt(directory):directory = os.path.normpath(directory)if not os.path.isdir(directory):raise IOError("The directory '" +"' desn't exist!")paths = []for curdir, subdirs, files in \os.walk(directory):for txt in (file for filein files if file.endswith('.txt')):path = os.path.join(curdir, txt)paths.append(path)return pathscount=0
paths = search_txt(r'F:\txt文件夹')
fontname='宋体'
for path in paths:pathname = path.split('\\')pathname=pathname[-1]pathname=pathname.strip('.txt')count += 1print(count)with open(path, "r",encoding='utf-8') as fp:s= fp.read()# 新建空白文档doc1 = Document()# 创建段落,添加文档内容run = doc1.add_paragraph().add_run(s)run.font.size = Pt(14)run.font.name=fontnamer = run._elementr.rPr.rFonts.set(qn('w:eastAsia'), fontname)# 保存文件doc_name = 'F:/word文件夹/'+str(count)+'_'+fontname+'_'+pathname+'.docx'doc1.save(doc_name)
这篇关于python实现txtSaveAsWord txt文件另存为word的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!