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.
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. To add a title or heading we will use the inbuilt .add_heading() method of the document object.
Syntax: doc.add_heading(String s, level)
- String s: It is the string data that is to be added as a heading or a title.
- level: It is an integer number in the range 0-9. It raises ValueError if any value other than from this range is given as input.
When the level is set to 0, the string is printed as the title of the document. For all other values it prints a heading. The size of heading decreases as the level increases. If no level is set, by default its value is always 1.
Pip command to install this module is:
pip install python-docx
- Import module
- Declare docx object
- Use add_heading() with appropriate parameters to add heading
- Save doc file.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.