python txt转word
时间: 2023-10-01 22:05:38 浏览: 82
你可以使用Python中的`docx`库将txt文件转换为Word文档。你需要先安装`docx`库,可以使用以下命令进行安装:
```
pip install python-docx
```
然后,你可以使用以下Python代码将txt文件转换为Word文档:
```python
import docx
# 打开txt文件
with open('file.txt', 'r') as f:
text = f.read()
# 创建一个新的Word文档
doc = docx.Document()
# 将txt内容写入Word文档中
doc.add_paragraph(text)
# 保存Word文档
doc.save('file.docx')
```
这将创建一个名为`file.docx`的Word文档,其中包含了`file.txt`中的文本内容。
相关问题
python批量txt转word
你可以使用 Python 的 `docx` 库和 `os` 库来实现批量将 txt 文件转换为 word 文件。
以下是一个示例代码,具体可以根据自己的需求进行修改:
```python
from docx import Document
import os
# 设置工作路径
work_path = 'your_work_path'
# 遍历所有 txt 文件
for filename in os.listdir(work_path):
if filename.endswith('.txt'):
# 读取 txt 文件
with open(os.path.join(work_path, filename), 'r', encoding='utf-8') as f:
content = f.read()
# 创建 word 文档
doc = Document()
# 添加内容
doc.add_paragraph(content)
# 保存为 word 文件
doc.save(os.path.join(work_path, filename.replace('.txt', '.docx')))
```
你只需要将 `your_work_path` 替换为你的工作路径即可。注意,需要安装 `docx` 库。可以使用以下命令安装:
```
pip install python-docx
```
python word转txt
要将Word文档转换为txt文件,可以使用Python中的python-docx库来实现。首先,确保已经安装了该库,然后按照以下步骤进行操作:
1. 导入所需的模块:
```python
from docx import Document
```
2. 打开Word文档:
```python
doc = Document('your_word_file.docx') # 替换 'your_word_file.docx' 为你的Word文件路径
```
3. 循环遍历文档中的段落,并将其写入txt文件:
```python
with open('output.txt', 'w', encoding='utf-8') as file:
for paragraph in doc.paragraphs:
file.write(paragraph.text + '\n')
```
其中,'output.txt' 是保存txt文件的路径和名称。
完整的代码如下所示:
```python
from docx import Document
doc = Document('your_word_file.docx')
with open('output.txt', 'w', encoding='utf-8') as file:
for paragraph in doc.paragraphs:
file.write(paragraph.text + '\n')
```
请替换 'your_word_file.docx' 为你的Word文档路径,然后运行以上代码即可将Word文档转换为txt文件。