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





