# 主要用于读取 文件的内容 def getContent ( file_path ) : f = open ( file_path , 'r' , encoding = 'UTF-8' ) content = f . read ( ) f . close ( ) return content # 将读取的内容追加至word文件中 # 首先进行word文件的判断,若不存在则先建立word def append2doc ( file_path , gen_path ) : if not os . path . exists ( gen_path ) : document = Document ( ) #声明word document . styles [ 'Normal' ] . font . name = u 'Times New Roman' #设置word字体,可以随意设置 document . styles [ 'Normal' ] . _element . rPr . rFonts . set ( qn ( 'w:eastAsia' ) , u 'Times New Roman' ) #设置word字体,可以随意设置 content = getContent ( file_path ) # 读取文件内容 document . add_paragraph ( content ) # 写入word document . save ( gen_path ) # 保存word else : document = Document ( gen_path ) document . styles [ 'Normal' ] . font . name = u 'Times New Roman' document . styles [ 'Normal' ] . _element . rPr . rFonts . set ( qn ( 'w:eastAsia' ) , u 'Times New Roman' ) paragraphs = document . paragraphs paragraphs [ - 1 ] . runs [ - 1 ] . add_break ( WD_BREAK . LINE ) #在最后位置 追加内容 content = getContent ( file_path ) paragraphs [ - 1 ] . add_run ( content ) document . save ( gen_path ) # for循环定义了相应遍历的文件夹地址 for path in [ '/' , '/back/' , '/templates/' ] : # 'G:/Pycharm/chajian/web'是我的固定路径 + file_path 是真正遍历的文件夹地址 for file_path in os . listdir ( 'G:/Pycharm/chajian/web' + path ) : try : # finally.docx 为最后生成的word文档 名称可以自己修改 append2doc ( 'G:/Pycharm/chajian/web' + path + file_path , 'finally.docx' ) except : # 输出失败的文件地址 print ( file_path ) 在很多时候编写 python 代码要和文件进行交互只能使用file函数,但是file函数有 一个 缺点,就是只能对文本文档进行读写操作。那有没有什么办法能够将数据存入到 word 文件中呢,下面这篇文章五步教会你怎么向 word 写入 数据。 Talk is cheap show me the code!(我来翻译一哈:不bb上代码) import os os.chdir('D:\\ python _major\\auto_office14') import datetime from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.shared import Pt, RGBColor from docx.oxml.ns im 一、POI 写入 word 文档 首先参考W3Shool的教程(上述快速指南)的“Apache POI Word - 文档”一节,对于创建文档和 写入 段落都有清晰的阐释。我不再赘述。但是其 写入 段落的方式每次都会覆盖曾经 写入 内容 。那么经过我探索一番要这么处理... 二、POI 追加 写入 word 文档 W3SHOOL教程段落覆盖是因为每次都会重建已经存... 使用 Python 办公自动化:将文本、表格及图片 写入 Word ,其中包含 写入 文本到 Word 中的一些常用函数,并含有 写入 表格与图片到 Word 中的常用函数,还有控制段落、字体样式的相关语句。 file=docx.Document()#创建内存中的 word 文档对象 file.add_paragraph("窗前明月光")# 写入 若干段落 file.add_paragraph("疑是地上霜") file.add_paragraph("举头望明月") file.add_paragraph("低头思故乡") file.save("E:\desktop\静夜思.docx"... Python 操作 Word 用到了模块,它把 word 分割成很多段落,如下结构:其中document是整个文档对象,paragraph是段落run是段落下的按照样式来分割的小块,每块有独立的样式。 首先要下载库 Python -docx.可以直接pip下载,pip install python -docx# coding:utf-8from docx import Documentfrom docx.shared import Inchesdocument = Document()document.add_heading(u' Python 操作 Word 实例', 3) #直接添加标题#先定义标题... 一,简介上一篇已经介绍了 python -docx模块的安装和导入,本篇直接介绍如何创建并 写入 word 文档,需要注意的是:创建 word 写入 之后,操作的都是内存中的对象,最后需要保存到文件,才能看到真实的文件。二,代码演示非常简单,直接演示代码和执行结果:#创建并 写入 word 文档 import docx#创建内存中的 word 文档对象 file=docx.Document()# 写入 若干段落 file.ad