07-第1步_找到所有PDF文档
第1步:找到所有PDF文档
首先,程序需要取得当前工作目录中所有带.pdf扩展名的文档列表,并对它们排序。让你的代码看起来像这样:
#! python3
# combinePdfs.py - Combines all the PDFs in the current working directory into
# into a single PDF.
❶ import PyPDF2, os
# Get all the PDF filenames.
pdfFiles = []
for filename in os.listdir('.'):
if filename.endswith('.pdf'):
❷ pdfFiles.append(filename)
❸ pdfFiles.sort(key = str.lower)
❹ pdfWriter = PyPDF2.PdfFileWriter()
# TODO: Loop through all the PDF files.
# TODO: Loop through all the pages (except the first) and add them.
# TODO: Save the resulting PDF to a file.
在 #! 行和介绍程序做什么的描述性注释之后,代码导入了 os 和 PyPDF2 模块❶。 os.listdir('.') 调用将返回当前工作目录中所有文档的列表。代码循环遍历这个列表,将带有 .pdf 扩展名的文档添加到 pdfFiles 中❷。然后,列表按照字典顺序排序,调用 sort() 时需要带有 key/str.lower 关键字参数❸。
代码创建了一个 PdfFileWriter 对象,以保存合并后的PDF页面❹。最后,使用一些注释语句简要描述了剩下的程序。