Python合并同一个文件夹下所有PDF文件的方法

yipeiwu_com5年前Python基础

一、需求说明

下载了网易云课堂的吴恩达免费的深度学习的pdf文档,但是每一节是一个pdf,我把这些PDF文档放在一个文件夹下,希望合并成一个PDF文件。于是写了一个python程序,很好的解决了这个问题。

二、数据形式

三、合并效果

四、python代码实现

# -*- coding:utf-8*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import os.path
from pyPdf import PdfFileReader,PdfFileWriter
import time
time1=time.time()
# 使用os模块walk函数,搜索出某目录下的全部pdf文件
######################获取同一个文件夹下的所有PDF文件名#######################
def getFileName(filepath):
  file_list = []
  for root,dirs,files in os.walk(filepath):
    for filespath in files:
      # print(os.path.join(root,filespath))
      file_list.append(os.path.join(root,filespath))
  return file_list
##########################合并同一个文件夹下所有PDF文件########################
def MergePDF(filepath,outfile):
  output=PdfFileWriter()
  outputPages=0
  pdf_fileName=getFileName(filepath)
  for each in pdf_fileName:
    print each
    # 读取源pdf文件
    input = PdfFileReader(file(each, "rb"))
    # 如果pdf文件已经加密,必须首先解密才能使用pyPdf
    if input.isEncrypted == True:
      input.decrypt("map")
    # 获得源pdf文件中页面总数
    pageCount = input.getNumPages()
    outputPages += pageCount
    print pageCount
    # 分别将page添加到输出output中
    for iPage in range(0, pageCount):
      output.addPage(input.getPage(iPage))
  print "All Pages Number:"+str(outputPages)
  # 最后写pdf文件
  outputStream=file(filepath+outfile,"wb")
  output.write(outputStream)
  outputStream.close()
  print "finished"
if __name__ == '__main__':
  file_dir = r'D:/course/'
  out=u"第一周.pdf"
  MergePDF(file_dir,out)
  time2 = time.time()
  print u'总共耗时:' + str(time2 - time1) + 's'
"D:\Program Files\Python27\python.exe" D:/PycharmProjects/learn2017/合并多个PDF文件.py
D:/course/C1W1L01 Welcome.pdf
3
D:/course/C1W1L02 WhatIsNN.pdf
4
D:/course/C1W1L03 SupLearnWithNN.pdf
4
D:/course/C1W1L04 WhyIsDLTakingOff.pdf
3
D:/course/C1W1L05 AboutThisCourse.pdf
3
D:/course/C1W1L06 CourseResources.pdf
3
All Pages Number:20
finished
总共耗时:0.128000020981s
Process finished with exit code 0

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

用pytorch的nn.Module构造简单全链接层实例

python版本3.7,用的是虚拟环境安装的pytorch,这样随便折腾,不怕影响其他的python框架 1、先定义一个类Linear,继承nn.Module import tor...

django初始化数据库的实例

最近项目需要,需要在表创建好之后,初始化一些数据。Django初始化数据的方法有很多,但都需要额外的手动操作,不智能。 看网上有一种方法用post_syncdb信号来初始化数据库,但是我...

PyQt5每天必学之工具提示功能

PyQt5每天必学之工具提示功能

本文将教会我们如何使用PyQt5控件的工具提示功能。 #!/usr/bin/python3 # -*- coding: utf-8 -*- """ PyQt5 教程 这个例子显示...

Python实现Windows和Linux之间互相传输文件(文件夹)的方法

Python实现Windows和Linux之间互相传输文件(文件夹)的方法

项目中需要从Windows系统传输ISO文件到Linux测试系统,然后再Linux测试系统里安装这个ISO文件。所以就需要实现如何把文件从Windows系统传输到Linux系统中。 在项...

Python每天必学之bytes字节

Python中的字节码用b'xxx'的形式表示。x可以用字符表示,也可以用ASCII编码形式\xnn表示,nn从00-ff(十六进制)共256种字符。 一、基本操作 下面列举一下字节的基...