Text-Replace in docx and save the changed file with python-docx

前端 未结 8 849
小鲜肉
小鲜肉 2021-01-02 07:04

I\'m trying to use the python-docx module to replace a word in a file and save the new file with the caveat that the new file must have exactly the same formatting as the ol

8条回答
  •  无人及你
    2021-01-02 07:48

    this worked for me:

    def docx_replace(old_file,new_file,rep):
        zin = zipfile.ZipFile (old_file, 'r')
        zout = zipfile.ZipFile (new_file, 'w')
        for item in zin.infolist():
            buffer = zin.read(item.filename)
            if (item.filename == 'word/document.xml'):
                res = buffer.decode("utf-8")
                for r in rep:
                    res = res.replace(r,rep[r])
                buffer = res.encode("utf-8")
            zout.writestr(item, buffer)
        zout.close()
        zin.close()
    

提交回复
热议问题