【发布时间】:2016-03-13 17:11:18
【问题描述】:
我有两个文件名相同的 PDF 文件夹。我想遍历第一个文件夹,获取文件名的前 3 个字符,将其设为“当前”页面名称,然后使用该值从两个文件夹中获取 2 个相应的 PDF,合并它们,并将它们写入第三个文件夹。
下面的脚本在第一次迭代中按预期工作,但在那之后,后续合并的 PDF 包括所有以前的 PDF(在 8 次迭代中迅速膨胀到 72 页)。
其中一些可能是由于代码不佳,但我不知道那在哪里,或者如何清除可能导致每次迭代仅写入 2 页失败的输入/输出:
import os
from PyPDF2 import PdfFileMerger
merger = PdfFileMerger()
rootdir = 'D:/Python/Scatterplots/BoundaryEnrollmentPatternMap'
for subdir, dirs, files in os.walk(rootdir):
for currentPDF in files:
#print os.path.join(file[0:3])
pagename = os.path.join(currentPDF[0:3])
print "pagename is: " + pagename
print "File is: " + pagename + ".pdf"
input1temp = 'D:/Python/Scatterplots/BoundaryEnrollmentPatternMap/' + pagename + '.pdf'
input2temp = 'D:/Python/Scatterplots/TraditionalScatter/' + pagename + '.pdf'
input1 = open(input1temp, "rb")
input2 = open(input2temp, "rb")
merger.append(fileobj=input1, pages=(0,1))
merger.append(fileobj=input2, pages=(0,1))
outputfile = 'D:/Python/Scatterplots/CombinedMaps/Sch_' + pagename + '.pdf'
print merger.inputs
output = open(outputfile, "wb")
merger.write(output)
output.close()
#clear all inputs - necessary?
outputfile = []
output = []
merger.inputs = []
input1temp = []
input2temp = []
input1 = []
input2 = []
print "done"
我的代码/工作基于此示例:
https://github.com/mstamy2/PyPDF2/blob/master/Sample_Code/basic_merging.py
【问题讨论】:
标签: python pdf pdf-generation pypdf