python合并多个pdf为一个pdf

该代码示例演示了如何使用Python的PyPDF2库安装、导入并合并PDF文件。首先,通过pip安装或升级PyPDF2,然后读取指定目录下的PDF文件,过滤出.pdf格式的文件,创建一个PdfWriter对象将这些文件合并,并将结果写入到指定的输出路径。在运行过程中,注意处理可能的错误,如文件类型不匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        确保安装该库:

```

pip install PyPDF2

``` 

最新版

```

pip install --upgrade PyPDF2

```

查看版本号

```

pip show PyPDF2

```

import os
# 需要先下载PyPDF2
from PyPDF2 import PdfWriter, PdfFileReader

folder_path = '你存放文件的目录'
output_path = '需要存放的地址merged_file.pdf'

def get_files_in_directory(directory):
    file_list = []
    for root, directories, files in os.walk(directory):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            file_list.append(file_path)
    return file_list

# 获取所有文件名
filenames = get_files_in_directory(folder_path)

# 除去目录中不是以pdf结尾的文件
filtered_list = [file for file in filenames if file.endswith('.pdf')]


merger = PdfWriter()

for pdf in filtered_list:
    merger.append(pdf)

merger.write(output_path)

merger.close()

如果报错:

```

Traceback (most recent call last):
  File "c:\Users\32658\Desktop\func_script\merge_pdf.py", line 28, in <module>
    merger.write(output_path)
  File "E:\Code\Python\Lib\site-packages\PyPDF2\_writer.py", line 986, in write
    stream = FileIO(stream, "wb")
             ^^^^^^^^^^^^^^^^^^^^

``` 

记得输出路径要:E:\desktop_files\数学要素.pdf

最后是你要输出的文件(名称,格式),而不只是文件路径。

more reading:

```

Installation — PyPDF2 documentation

```

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值