Adding a Paragraph
To add a paragraph in a word document we make use the inbuilt method add_paragraph() to add a paragraph in the word document. By using this method we can even add paragraphs which have characters like ‘\n’, ‘\t’ and ‘\r’. Apart from that, we can also add various styles to it.
Syntax: doc.add_paragraph(String s, style=None)
Parameters:
- String s: It is the string data that is to be added as a paragraph. This string can contain newline character ‘\n’, tabs ‘\t’ or a carriage return character ‘\r’.
- style: It is used to set style.
Example 1: Python program to add a paragraph in a Word document.
Python3
# Import docx NOT python-docx import docx # Create an instance of a word document doc = docx.Document() # Add a Title to the document doc.add_heading( 'w3wiki' , 0 ) # Adding paragraph doc.add_paragraph( 'w3wiki is a Computer Science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes etc.' ) # Now save the document to a location doc.save( 'gfg.docx' ) |
Output:
A multiline paragraph can be inserted by giving a multiline string input in the method, which can be done easily by using three single quotes ”’ w3wiki ”’.
Example 2: Python program to add multiline paragraphs in a word document.
Python3
# Import docx NOT python-docx import docx # Create an instance of a word document doc = docx.Document() # Add a Title to the document doc.add_heading( 'w3wiki' , 0 ) # Adding multilined paragraph doc.add_paragraph( '''w3wiki is a Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes etc.''' ) # Now save the document to a location doc.save( 'gfg.docx' ) |
Output:
Working with Paragraphs in Python .docx Module
Prerequisites: docx
Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. Pip command to install this module is:
pip install python-docx
Python docx module allows user to manipulate docs by either manipulating the existing one or creating a new empty document and manipulating it. It is a powerful tool as it helps you to manipulate the document to a very large extend.
Contact Us