Python中读写`.docx`文件可以使用`python-docx`库。以下是使用`python-docx`库进行文件读取和保存的基本步骤:
安装`python-docx`库
在命令行或终端中输入以下命令来安装`python-docx`库:
pip install python-docx
读取`.docx`文件
import docx
打开文档
doc = docx.Document('path_to_your_file.docx')
读取文档内容
for paragraph in doc.paragraphs:
print(paragraph.text)
读取表格内容
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
print(cell.text)
保存`.docx`文件
import docx
新建文档
doc_new = docx.Document()
添加内容
doc_new.add_paragraph('Hello, World!')
保存文档
doc_new.save('new_file.docx')
注意事项
确保`.docx`文件的路径正确。
如果需要编辑现有文档,`python-docx`库也提供了相应的功能,可以修改文字、样式、布局等。
以上是使用`python-docx`库进行`.docx`文件读写的基本操作。