Python Learning: Automate Boring Stuff with Python | Chapter 13: Custom Invitations as Word Documents

“Nothing annoys people so much as not receiving invitations.”
― Oscar Wilde, The Importance of Being Earnest

I know that feeling…humph.. 10:36:20 PM


 


#usage python invitation.py <textFile>


import docx, os, sys, logging 
from docx.enum.text import WD_ALIGN_PARAGRAPH
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")


if len( sys.argv ) == 2:
	#TODO: GET TEXT FILE 
	textFileName = sys.argv[1]
	textFileName = os.path.abspath(textFileName)
	#TODO: TEST IF EXISTS
	if not os.path.exists(textFileName):
		logging.error("File does not exist")
		raise
	#TODO: READ FILE 
	file = open(textFileName)
	#TODO: CREATE DOCX OBJECT
	doc = docx.Document()
	names = file.readlines()
	for name in names:
		name = name.strip()
		#TODO: CREATE INVITATION PER NAME
		p = doc.add_paragraph("", "Normal")
		p.alignment  = WD_ALIGN_PARAGRAPH.CENTER
		p.add_run("It would be a pleasure to have the company of").italic = True
		p = doc.add_paragraph("", "Title")
		p.alignment  = WD_ALIGN_PARAGRAPH.CENTER
		r = p.add_run(name)
		r.bold = True
		r.all_caps = True
		p = doc.add_paragraph("", "Normal")
		p.alignment  = WD_ALIGN_PARAGRAPH.CENTER
		p.add_run("at 1101 Memory Lane on the Evening of").italic = True
		p = doc.add_paragraph("", "Normal")
		p.alignment  = WD_ALIGN_PARAGRAPH.CENTER
		p.add_run("April 1st")
		p = doc.add_paragraph("", "Normal")
		p.alignment  = WD_ALIGN_PARAGRAPH.CENTER
		p.add_run("at 7 o' clock").italic =True
		doc.add_page_break()
	#TODO: SAVE DOCUMENT
	doc.save("guest_invitation.docx")
	logging.info("Invitations completed")
	file.close()

else:
	logging.error("usage python invitation.py <textFile>")
<span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_start"></span>

As always we will see in the next post!