python读取docx的文本并存为txt
时间: 2024-05-05 19:17:42 浏览: 7
可以使用Python的`python-docx`库来读取docx文件中的文本,并将其保存为txt文件。以下是一段示例代码:
```python
import docx
# 打开docx文件
doc = docx.Document("example.docx")
# 读取文本
text = ""
for para in doc.paragraphs:
text += para.text
# 将文本保存为txt文件
with open("example.txt", "w", encoding="utf-8") as f:
f.write(text)
```
首先,使用`docx.Document`函数打开docx文件。然后,使用`doc.paragraphs`属性遍历文档中的所有段落,并将它们的文本拼接到一个字符串中。最后,使用`open`函数创建一个txt文件,并将文本写入其中。
相关问题
python批量docx转换为txt
可以使用Python库docx2txt来批量将docx文档转换为txt文本文件。可以使用以下代码:
```
import docx2txt
import os
# 创建一个文件夹用于存储转换后的txt文本文件
if not os.path.exists('txt_files'):
os.makedirs('txt_files')
# 遍历所有docx文件并转换为txt文本文件
for filename in os.listdir('.'):
if filename.endswith('.docx'):
text = docx2txt.process(filename)
with open(f'txt_files/{filename[:-5]}.txt', 'w') as f:
f.write(text)
```
这个代码遍历当前文件夹中所有的docx文件,并将其转换为txt文本文件,并将它们保存在一个名为'txt_files'的文件夹中。
python 读取docx
以下是Python读取docx文件的示例代码:
```python
import docx
# 打开文档
doc = docx.Document('demo.docx')
# 遍历文档中的段落
for para in doc.paragraphs:
# 打印段落的文本内容
print(para.text)
# 遍历文档中的表格
for table in doc.tables:
# 遍历表格中的行
for row in table.rows:
# 遍历行中的单元格
for cell in row.cells:
# 打印单元格的文本内容
print(cell.text)
```
这段代码使用了Python的docx库来读取docx文件。首先,我们需要使用`docx.Document()`函数打开一个docx文件,然后可以使用`doc.paragraphs`属性来遍历文档中的段落,使用`doc.tables`属性来遍历文档中的表格。对于每个段落和单元格,我们可以使用`.text`属性来获取其文本内容。