python -从文件夹批量提取pdf文章的第n页,并存储起来

python -从文件夹批量提取pdf文章的第n页,并存储起来

废话不多说,看下面代码

讲解一下下面代码

reader = PyPDF2.PdfReader (file)

将文件转化为PdfReader 对象,方便使用内置方法。

first_page = reader.pages[0]

提取第一页

writer = PyPDF2.PdfWriter ()

writer.add_page (first_page)

writer.write(output_file)

将代码写入对应位置

python 复制代码
def process_folder(folder_path):
    # 遍历文件夹中的所有文件
    for filename in os.listdir(folder_path):
        if filename.endswith('.pdf'):
            pdf_path = os.path.join(folder_path, filename)
            print(pdf_path)
            output_path = os.path.join('D:\data\pdf_output', filename[0:-4]+'(首页)'+'.pdf')
            # 提取第一页并保存为同名文件
            extract_first_page(pdf_path, output_path)
            print(f"Processed {filename}")

读取某个文件夹下的所有pdf文件,并调用函数取出第一页,并写下来。

python 复制代码
import os
import PyPDF2

def extract_first_page(pdf_path, output_path):
    # 打开PDF文件
    with open(pdf_path, 'rb') as file:
        reader = PyPDF2.PdfReader (file)
        # 获取第一页
        first_page = reader.pages[0]
        # 写入新PDF文件
        with open(output_path, 'wb') as output_file:
            writer = PyPDF2.PdfWriter ()
            writer.add_page (first_page)
            writer.write(output_file)

def process_folder(folder_path):
    # 遍历文件夹中的所有文件
    for filename in os.listdir(folder_path):
        if filename.endswith('.pdf'):
            
            pdf_path = os.path.join(folder_path, filename)
            print(pdf_path)
            output_path = os.path.join('D:\data\pdf_output', filename[0:-4]+'(首页)'+'.pdf')
            # 提取第一页并保存为同名文件
            extract_first_page(pdf_path, output_path)
            print(f"Processed {filename}")

# 指定你的文件夹路径
folder_path = 'D:\data\pdf'
process_folder(folder_path)
相关推荐
草莓熊Lotso5 小时前
Linux 文件描述符与重定向实战:从原理到 minishell 实现
android·linux·运维·服务器·数据库·c++·人工智能
历程里程碑5 小时前
Linux22 文件系统
linux·运维·c语言·开发语言·数据结构·c++·算法
恋猫de小郭5 小时前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
寻星探路10 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
崔庆才丨静觅11 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606112 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了12 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅12 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
ValhallaCoder12 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
wdfk_prog12 小时前
[Linux]学习笔记系列 -- [drivers][input]input
linux·笔记·学习