如何使用Python Docx或Python中可用的任何其他库删除Word文件中的空白页?
我有一个具有多个空白页面的DOCX格式的Word文档。我需要使用Python删除文档中的所有空白页面。我试图在文档中删除空行。但这是行不通的。 tried the below code:
from docx import *
document=Document("\\doc_path")
z=len(document.paragraphs)
for i in range(0,z):
if document.paragraphs[i].text=="":
document.paragraphs[i].clear()
The above-mentioned code is not working and deleting all the intermediate empty lines on a page.
I have a word document in Docx format which has multiple blank pages. I need to delete all the blank pages in the document using python. I have tried to delete empty lines in the document. But it is not working. tried the below code:
from docx import *
document=Document("\\doc_path")
z=len(document.paragraphs)
for i in range(0,z):
if document.paragraphs[i].text=="":
document.paragraphs[i].clear()
The above-mentioned code is not working and deleting all the intermediate empty lines on a page.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要使用Python-docx库中删除Word文档中的所有空白页面,您不仅需要考虑空的段落,还需要考虑其他元素,例如空表,空段或页面断路,可能会导致空白页。
'来自DOCX导入文档
=文档(“ doc_path”)
段落= document.Paragraphs
反向循环,以避免在
范围内删除i段落时索引错误(len(段落)-1,-1,-1):
如果段落[i] .text.strip()==“”:
document._body._body.remove(paragraphs[i]._element)
document.save("doc_path")
class ChoiceInvoice'
Like use this snippet.也许会有所帮助
To remove all blank pages from a Word document using the python-docx library, you need to consider not just empty paragraphs but also other elements like empty tables, empty sections, or page breaks that might be causing the blank pages.
'from docx import Document
document = Document("doc_path")
paragraphs = document.paragraphs
Reverse loop to avoid index errors when deleting paragraphs
for i in range(len(paragraphs) - 1, -1, -1):
if paragraphs[i].text.strip() == "":
document._body._body.remove(paragraphs[i]._element)
document.save("doc_path")
class ChoiceInvoice'
Like use this snippet. Maybe it will be helpful