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

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.

#! 行和介绍程序做什么的描述性注释之后,代码导入了 osPyPDF2 模块❶。 os.listdir('.') 调用将返回当前工作目录中所有文档的列表。代码循环遍历这个列表,将带有 .pdf 扩展名的文档添加到 pdfFiles 中❷。然后,列表按照字典顺序排序,调用 sort() 时需要带有 key/str.lower 关键字参数❸。

代码创建了一个 PdfFileWriter 对象,以保存合并后的PDF页面❹。最后,使用一些注释语句简要描述了剩下的程序。