問題描述
修改word中文本,如下代碼,保存時會導致word中的部分圖片消失
from docx import Document path1 = 'test_in.docx' path2 = 'test_out.docx' file = docx.Document(path1) for parg in file.paragraphs: if parg.text: parg.text = "test" + parg.text file.save(path2)
解決方案
file.inlineshapes僅能找到內聯圖片,非內聯圖片找不到,
但通過file.paragraphs[n].runs[m].element.drawing_lst 則可返回塊中的圖形列表,包括內聯圖形和非內聯圖形。所以圖片會存在paragraph.run內,如果直接修改paragraph.text會破壞paragraph結構,導致圖片丟失。
所以解決方案就是修改下一級run中text而不動圖片,如下:
from docx import Document path1 = 'test_in.docx' path2 = 'test_out.docx' file = docx.Document(path1) for parg in file.paragraphs: runt = [] for run in parg.runs: if run.text: runt.appent(run.text) runtext = '' parg.add_run('test***'+''.join(runt)) file.save(path2)
————————————————
版權聲明:本文為CSDN博主「SUN_SU3」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/u013546508/article/details/88747317