I have a function that prints text to the console. Below is a version of what the code looks like (it's actually a lot of lines of a story, so I'm summarizing it.) My question is - is there another function I can write to take all_text() and generate a docx file with the it? I've managed to create a .txt file, but I would ideally like to create something with formatting options.
from docx import Document
document = Document()
def all_text():
print("Line1\nLine2\nLine3")
document.add_paragraph(all_text())
document.save("demo.docx")
Document.add_paragraph()
expects a string. Your all_text()
function is not returning a string, but writing to sys.stdout
(which is by default redirected to your console) and (implicitely) returning None
.
The clean solution is of course to change your all_text()
function so that it returns a string instead of writing to sys.stdout
ie
def all_text():
return "Line1\nLine2\nLine3"
If your real function actually does a lot of printing in different places and/or call functions which themselves print to stdout etc, making the "clean solution" impractical or too expensive, you can also hack around by redirecting sys.stdout
to a StringIO
and sending the collected values to add_paragraph
, ie:
import sys
try:
from io import StringIO # py3
except ImportError:
from cStringIO import StringIO
def all_text():
print("Line1\nLine2\nLine3")
def get_all_text():
sys.stdout = buffer = StringIO
try:
all_text()
return buffer.getvalue()
finally:
sys.stdout = sys.__stdout__
document.add_paragraph(get_all_text())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.