1

I'm trying to write into tables in a word template my company uses for statement of works,
I already have working code that takes our template file and saves it as a new filename in a different location. The filepath+filename is new_SOWdst_file_name.

This keeps crashing usually for a failure error about this being not writeable.

Pretty new to python. Any advice appreciated.

# doc = Document(new_SOWdst_file_name)
# f = open(new_SOWdst_file_name, 'r')
# doc = Document(f)


# if customType == ca :
#     sys.exit()
    

# elif customType == sc :
#     SOWNum = doc.tables[0].cell(4,2).text
#     SOWAuthor = doc.tables[0].cell(6,2).text
#     SOWDescriptor = doc.tables[0].cell(8,2).text
#     SOWPartNum = doc.tables[0].cell(9,2).text
#     SOWDate = doc.tables[0].cell(13,1).text
    
#     SOWNum = 'SOW-'+ PartNum
#     SOWAuthor = 'Cody Nelson'
#     SOWDescriptor = Description
#     SOWPartNum = PartNum
#     SOWDate = now.strftime("%b %d, %Y")
    # doc.save(f)
    # f.close()
    # doc.close()
#     sys.exit()
    
# elif customType == cc :
#     sys.exit()
        
2
  • In line number 2, you are opening file in read mode 'r'. If you want to write to the file, you should open it in write mode 'w' i.e. change f = open(new_SOWdst_file_name, 'r') to f = open(new_SOWdst_file_name, 'w') Commented Jan 8, 2021 at 19:13
  • @Lambda I tried the above and anytime I try to open and save the docx like this the resulting document is saved into the location with the proper name but it opens as read only and is completely blank. Commented Jan 11, 2021 at 21:55

2 Answers 2

1

Don't open the file before reading or writing it. python-docx takes care of all those details for you. All you need is:

document = Document(new_SOWdst_file_name)
# ... do your work with `document`
document.save("new-file-name.docx")
Sign up to request clarification or add additional context in comments.

1 Comment

When I try this method nothing is saved into the document. None of the 'work' is done.
1
doc = Document(new_SOWdst_file_name)


doc.tables[0].cell(13,1).text = now.strftime("%b %d, %Y")
doc.tables[0].cell(9,2).text = PartNum
doc.tables[0].cell(8,2).text = Description
doc.tables[0].cell(6,2).text = 'Cody Nelson'
doc.tables[0].cell(4,2).text = 'SOW-'+ PartNum

doc.save(new_SOWdst_file_name)

Not sure why this works and the other doesn't. But, it works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.