当前位置:嗨网首页>书籍在线阅读

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 对象。