Python 删除 Word 文档特定行代码示例
要删除特定行的内容,你可以使用循环语句逐行读取 word 文档中的内容,并根据行号判断是否删除该行的内容。以下是一个示例代码:
from docx import Document
def delete_specific_lines(file_path, line_numbers):
doc = Document(file_path)
paragraphs = doc.paragraphs
# 逐行遍历并删除指定行
deleted_lines = 0 # 用于修正行号
for i in range(len(paragraphs)):
line_number = i + 1 - deleted_lines # 实际行号
if line_number in line_numbers:
del paragraphs[i]
deleted_lines += 1
# 保存修改后的文档
doc.save(file_path)
# 使用示例
file_path = 'your_file.docx'
line_numbers = [1, 6, 11, 16]
delete_specific_lines(file_path, line_numbers)
需要注意的是,这个示例代码使用了 python-docx 库来操作 Word 文档,因此你需要先通过 pip install python-docx 命令安装该库。此外,你需要将 your_file.docx 替换为你实际的文件路径。
原文地址: https://www.cveoy.top/t/topic/pdQY 著作权归作者所有。请勿转载和采集!