I have been using python-docx to create and save .docx files automatically. It works to create a single uniquely named .docx file, but if I want to overwrite that file it doesn't do anything.
I have tried doing os.remove, or deleting the file before running my program again, and still nothing.
The only thing which allows it to work is to go into the Recycle Bin and delete it permanently.
def writeDocx():
# os.remove(client+' Invoice.docx')
###heading at top###
document.add_heading(client+" Invoice", 0)
document.add_paragraph("").add_run("This Invoice was generated automatically").italic = True
table = document.add_table(rows=1, cols=3)
t = table.rows[0].cells
t[0].text = 'TEST'
t[1].text = 'TEST'
t[2].text = 'TEST'
for i in range(6):
row_cells = table.add_row().cells
row_cells[0].text = str(i)
row_cells[1].text = str(i)
row_cells[2].text = str(i)
document.save(client+' Invoice.docx')
It should overwrite already saved Invoice.docx file with the newly generated file, but it does not.
It shows no error messages.
document.save(filename)
will overwrite filename
if it exists.
Your code does not show where document
comes from, but the following should be enough to reproduce the behavior:
Document().save(filename)
I suggest you do this with a literal, like "Client Invoice.docx", which takes the name formation out of the possible causes.
If it is still problematic, I would look at permissions, like the user running Python
is able to both read and write the file, although I suppose that would raise an exception. The other thing to check is whether the file is being written to another directory; the default directory for a Python program is sometimes not the expected one.
You should study this document for help in refining your reproducible problem statement. Often following this process helps you see where you went wrong, but in any case, gives us more of what we need to go on to help you:
https://stackoverflow.com/help/minimal-reproducible-example