问题描述
修改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)

 python 操作 word 图片 消失

 

 

 

解决方案
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)

  

 python 操作 word 图片 消失

 

 

————————————————
版权声明:本文为CSDN博主「SUN_SU3」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u013546508/article/details/88747317

相关文章:

  • 2021-06-14
  • 2022-12-23
  • 2021-12-15
  • 2022-01-19
  • 2021-11-14
  • 2021-12-01
  • 2021-12-14
  • 2021-07-09
猜你喜欢
  • 2021-11-04
  • 2022-12-23
  • 2021-12-15
  • 2021-05-27
  • 2021-11-24
  • 2021-11-04
  • 2021-11-04
相关资源
相似解决方案