0
点赞
收藏
分享

微信扫一扫

python-docx 文档翻译(三)处理文档

像小强一样活着 2022-04-14 阅读 45
python
from docx import Document

document = Document()
document.save('test.docx')

这会从默认模板创建一个新文档,并将其保存到名为“test.docx”的文件中。所谓的“默认模板”其实就是一个没有内容的 Word 文件,和安装的 python-docx 包一起存放。它与 Word 文档的模板大致相同。

打开现有文档:

document = Document('existing-document-file.docx')`

可以传递打开的文件或 StringIO/BytesIO 流对象来打开或保存文档,如下所示:

f = open('foobar.docx', 'rb')
document = Document(f)
f.close()
# or
with open('foobar.docx', 'rb') as f:
    source_stream = StringIO(f.read())
document = Document(source_stream)
source_stream.close()
...
target_stream = StringIO()
document.save(target_stream)
举报

相关推荐

0 条评论