Python-docx 模块不覆盖相同的文件名

Python-docx module not overwriting same file name

我一直在使用 python-docx 来自动创建和保存 .docx 文件。它可以创建一个唯一命名的 .docx 文件,但如果我想覆盖该文件,它不会执行任何操作。

我试过 os.remove,或者再次删除 运行 我的程序之前的文件,但仍然没有。

唯一允许它工作的方法是进入回收站并将其永久删除。

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')

它应该用新生成的文件覆盖已经保存的 Invoice.docx 文件,但它没有。

它没有显示任何错误消息。

来自Python-Docx

的官方文档

The document.save("file.docx") function will not replace the existing file until it is opened as document object (document = Document("file.docx"))

但是如果你想要一个解决方法,你可以这样做

is_present = False
document = Document()
try:
  document = Document("Invoice.docx")
  is_present =True
except:
  pass

if is_present:
  document.save("old-Invoice.docx") # or you can delete it.
  document = Document()
document.add_heading("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 = 'TEST1'
t[1].text = 'TEST2'
t[2].text = 'TEST3'
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('Invoice.docx')

document.save(filename) 将覆盖 filename(如果存在)。

您的代码没有显示 document 的来源,但以下内容应该足以重现该行为:

Document().save(filename)

我建议您使用文字来执行此操作,例如 "Client Invoice.docx",这样可以排除可能的原因。

如果仍然有问题,我会查看权限,例如用户 运行 Python 能够读取和写入文件,尽管我认为这会引发异常。要检查的另一件事是文件是否正在写入另一个目录; Python 程序的默认目录有时不是预期的目录。

您应该研究此文档以帮助改进您的可重现问题陈述。通常遵循此过程可以帮助您了解哪里出了问题,但无论如何,它为我们提供了更多我们需要继续帮助您的内容:
https://whosebug.com/help/minimal-reproducible-example