2

I have a structured text on python. I want to save it to a docx file.

Something like

text = "A simple text\n Structured"

with open('docx_file.docx', 'w') as f:
    f.write(text)
Asddfg
  • 237
  • 3
  • 13

3 Answers3

7

Check python-docx package:

from docx import Document

document = Document()
document.add_heading('A simple text', level=1)
document.add_paragraph('some more text ... ')

document.save('docx_file.docx')
pmod
  • 10,450
  • 1
  • 37
  • 50
  • it is possible to save the full text (already containing meta characters) all at once without compromising the format? Or do I have to manually save each paragraph – Asddfg Mar 24 '20 at 22:24
  • if you already have the preformed text already to go, try just writing it to a file. You could also write any data you wanted to the document variable, extract the text from that, and then modify the headers. – Isacc Barker Mar 24 '20 at 22:37
  • ModuleNotFoundError: No module named 'exceptions' – rsc05 Jun 16 '22 at 13:31
  • @Anonymous it's the known problem with docx and python3, check this https://stackoverflow.com/a/44233838/356838 – pmod Aug 23 '22 at 14:09
0

A docx file is not a plain text file, so unless you want to not use a library for this, I recommend https://grokonez.com/python/how-to-read-write-word-docx-files-in-python-docx-module. Unless you need to use a "fancy" format like docx, I would recommend just writing plain text to a txt file.

Isacc Barker
  • 507
  • 4
  • 15
0

Here is the code that I have used to save a text string to a word document.

newfile = open("Result.doc", "w+")
newfile.write("Hello World!")
newfile.close()