如何使用Python Docx或Python中可用的任何其他库删除Word文件中的空白页?

发布于 2025-01-29 19:06:24 字数 408 浏览 4 评论 0原文

我有一个具有多个空白页面的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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏花。依旧 2025-02-05 19:06:24

要使用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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文