08-第2步_打开每个PDF文档
第2步:打开每个PDF文档
现在,程序必须读取 pdfFiles
中的每个PDF文档。在程序中加入以下代码:
#! python3
# combinePdfs.py - Combines all the PDFs in the current working directory into
# a single PDF.
import PyPDF2, os
# Get all the PDF filenames.
pdfFiles = []
--snip--
# Loop through all the PDF files.
for filename in pdfFiles:
pdfFileObj = open(filename, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
# TODO: Loop through all the pages (except the first) and add them.
# TODO: Save the resulting PDF to a file.
针对每个PDF文档,循环内的代码调用 open()
,以 'wb'
作为第二个参数,用读二进制的模式打开文档。 open()
调用会返回一个 File
对象,它被传递给 PyPDF2.PdfFileReader()
,以创建针对那个PDF文档的 PdfFileReader
对象。