How to save text content to word in python

To save text content into Word, you can use the python-docx library in Python. First, make sure the library is installed, which can be installed with the following command:

```python
pip install python-docx
```

接下来,可以使用以下示例代码将文本保存到Word中:

```python
from docx import Document

# 创建一个新的Word文档
document = Document()

# 添加文本内容到文档中
document.add_paragraph("这是第一段文本。")
document.add_paragraph("这是第二段文本。")

# 保存文档
document.save("output.docx")
```

In the above example, the `Document` class is first imported and then a new Word document object is created. Text content is then added to the document using the `add_paragraph` method. Finally save the document as a file named "output.docx" by calling the `save` method.

After running the above code, a Word document named "output.docx" will be created in the directory where the script is located, and the text content will be saved in it.

Guess you like

Origin blog.csdn.net/qq_26429153/article/details/131785596