How to use word with Python with python-docx

A script that asks many things to the user and after that it saves all the questions and answers into a word document. It uses the python-docx module to:

  • create an instance of Document
  • iterate trough a list to input something from the user
  • sove the inputs and outputs in a docx file
from docx import Document
from docx.shared import Inches
import os
'''
Copyright Giovanni Gatto
published on https://pythonprogramming.altervista.org
04.06.2021

Gets inputs from external file and publish result with
answers into another docx file

Uses python-docx module and built-in os module
v.0.1
'''

document = Document()

def get_questions(ask:str="file_to_open.txt", output="output.docx"):
	''' opens a file with a sequence of inputs '''
	'''
	ask		name of the file where the input text are
	output  the docx document with the result of the answers
	'''

	# opens a file that is in the string ask argument
	with open(ask) as file:
		ask = file.read()
	
	for line in ask.splitlines():
		a = input(line + " : ")
		document.add_paragraph(line + ": " + a)

	document.save(output)
	os.startfile(output)

get_questions()

Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.