当我在 python 中保存 docx 文件时,数据被损坏

When I save the docx file in python, data gets corrupted

我可以毫无问题地编辑和保存 txt,但是当我保存 docx 文件时,数据会损坏。喜欢这里的图片:image of error 有什么正确保存 docx 的建议吗?谢谢

    def save(self,MainWindow):
        if self.docURL == "" or self.docURL.split(".")[-1] == "txt":
            text = self.textEdit_3.toPlainText()
            file = open(self.docURL[:-4]+"_EDITED.txt","w+")
            file.write(text)
            file.close()
        elif self.docURL == "" or self.docURL.split(".")[-1] == "docx":
            text = self.textEdit_3.toPlainText()
            file = open(self.docURL[:-4] + "_EDITED.docx", "w+")
            file.write(text)
            file.close()

.docx 文件不仅仅是文本 - 它们实际上是具有非常特定格式的 XML 文件的集合。要轻松 read/write 它们,您需要 python-docx 模块。调整您的代码:

from docx import Document

...

elif self.docURL == "" or self.docURL.split(".")[-1] == "docx":
    text = self.textEdit_3.toPlainText()
    doc = Document()
    paragraph = doc.add_paragraph(text)
    doc.save(self.docURL[:-4] + "_EDITED.docx"

一切就绪。关于文本格式设置、插入图像和形状、创建表格等,您可以做更多很多,但这会让您继续前进。我链接到上面的文档。