search
HomeBackend DevelopmentPython TutorialHow to read and write docx files in Python

How to read and write docx files in Python

May 08, 2018 am 11:57 AM
docxpythonmethod

这篇文章主要介绍了关于Python读写docx文件的方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

Python读写word文档有现成的库可以处理。我这里采用 python-docx。可以用pip install python-docx安装一下。

这里说一句,ppt和excel也有类似的库哦,而且是直接读取文件里面的xml数据。所以doc格式得另找其他库处理,doc格式不是基于xml的。

1、新建或打开文件。这个比较简单用docx的Document类,若指定路径则是打开文档;若没有指定路径则是新建文档

#coding:utf-8
import docx
 
#新建文档
doc_new = docx.Document()
 
#读取文档
doc = docx.Document(ur'C:\1.docx')

2、保存文件。有打开,就有保存。用Document类的save方法,其中参数是保存的文件路径,或者要保存的文件流。一般指定路径即可。

doc.save(path_or_stream)

3、对象集合。python-docx包含了word文档的相关对象集合。

doc.paragraphs #段落集合
doc.tables #表格集合
doc.sections #节 集合
doc.styles #样式集合
doc.inline_shapes #内置图形 等等...

4、插入段落。段落是word最基本的对象之一。

doc.add_paragraph(u'第一段',style=None) #插入一个段落,文本为“第一段”
#默认是不应用样式,这里也可以不写style参数,或者指定一个段落样式
doc.add_paragraph(u'第二段',style='Heading 2')
 
#这些样式都是word默认带有的样式,可以直接罗列出来有哪些段落样式
print [s.name for s in doc.styles if s.type==1]

5、新增样式。这个帮助文档里面说得不仔细,而且还是英文的。我手头上的项目用到这个,就自己琢磨出怎么使用,如下。

#coding:utf-8
from docx import Document
from docx.shared import RGBColor #这个是docx的颜色类
 
#新建文档
doc = Document()
 
#新增样式(第一个参数是样式名称,第二个参数是样式类型:1代表段落;2代表字符;3代表表格)
style = doc.styles.add_style('style name 1', 2)
 
#设置具体样式(修改样式字体为蓝色,当然还可以修改其他的,大家自己尝试)
style.font.color.rgb = RGBColor(0x0, 0x0, 0xff)

6、应用字符样式。字符自然是在段落里面的,可以采用下面方法给段落追加文字和设置字符样式。

#插入一个空白段落
p = doc.add_paragraph('')
p.add_run('123', style="Heading 1 Char")
p.add_run('456')
p.add_run('789', style="Heading 2 Char")
 
#这样一个段落就应用了两个字符样式,中间“456”就没应用样式
print p.text #输出结果是u'123456789' 也还是连续的

7、设置字体。当然可以不用通过设置样式对某些字进行设置,也可以直接设置。

p = doc.add_paragraph('')
r = p.add_run('123')
r.font.bold = True #加粗
r.font.italic = True #倾斜 等等...

8、表格操作。表格也是经常用到的一种对象类型。

#新建一个2x3的表格,style可以不写
table=doc.add_table(rows=2,cols=3,style=None)
 
#可以用table 的rows和columns得到这个表格的行数和列数
print len(table.rows)
print len(table.columns)
 
#遍历表格
for row in table.rows:
 row.cells[0].text = '1'
 #print row.cells[0].text
 
#新增行或列
table.add_row()
table.add_column()

Word常见操作差不多就是这些。大家可以查看帮助文档,也可以用dir和help查看对象的方法属性和帮助。

相关推荐:

Python读写/追加excel文件Demo

用Python读写Excel文档

The above is the detailed content of How to read and write docx files in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

Python List Concatenation Performance: Speed ComparisonPython List Concatenation Performance: Speed ComparisonMay 08, 2025 am 12:09 AM

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

How do you insert elements into a Python list?How do you insert elements into a Python list?May 08, 2025 am 12:07 AM

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.