将多个txt文本内容读取到一个word
时间: 2023-11-29 19:04:24 浏览: 34
你可以使用Python的`docx`库和`os`库来实现将多个txt文本内容读取到一个Word文档中。以下是实现的步骤:
1.导入`docx`和`os`库
```python
import docx
import os
```
2.获取所有txt文件的文件名
```python
# 获取所有txt文件的文件名
txt_files = [f for f in os.listdir('.') if f.endswith('.txt')]
```
这将获取当前目录下所有以`.txt`结尾的文件名。
3.将所有txt文件的内容写入Word文档
```python
# 创建一个新的Word文档
doc = docx.Document()
# 遍历所有txt文件,将内容写入Word文档
for txt_file in txt_files:
with open(txt_file, 'r') as f:
text = f.read()
doc.add_paragraph(text)
# 保存Word文档
doc.save('all_text.docx')
```
这将创建一个名为`all_text.docx`的Word文档,其中包含了所有txt文件中的文本内容。
完整的代码如下:
```python
import docx
import os
# 获取所有txt文件的文件名
txt_files = [f for f in os.listdir('.') if f.endswith('.txt')]
# 创建一个新的Word文档
doc = docx.Document()
# 遍历所有txt文件,将内容写入Word文档
for txt_file in txt_files:
with open(txt_file, 'r') as f:
text = f.read()
doc.add_paragraph(text)
# 保存Word文档
doc.save('all_text.docx')
```
注意,这将在当前目录下创建一个新的Word文档。如果需要保存到其他路径,可以修改保存路径。