问题
Here is the code block that is causing the issue. The loop will append the new file each time, which is not what I am trying to accomplish. For example, outputfile1 is input1.pdf, outputfile2 is input1.pdf + input2.pdf...
I am trying to merge file 1x.pdf with files 1a.pdf + 1b.pdf + 1c.pdf into the output file1.pdf and then loop through and do the same thing for 2, 3, and 4. The end result should be 4 separate files. What am I missing? Clear as mud? Thanks in advance for any assistance.
i = 1
while i < 5:
# files to be merged
input1 = open(Path1+str(i)+"x.PDF", "rb")
input2 = open(Path2+str(i)+"a.PDF", "rb")
input3 = open(Path2+str(i)+"b.PDF", "rb")
input4 = open(Path2+str(i)+"c.PDF", "rb")
# output files
output_file = open("/NewFile"+str(i)+".pdf", "wb")
# add input1 document to output
merger.append(fileobj = input1, pages = (0, 3, 2), import_bookmarks = False)
# insert the pages of input2 into the output beginning after the second page
merger.append(input2)
# insert the pages of input3 into the output beginning after the second page
merger.append(input3)
# insert the pages of input4 into the output beginning after the second page
merger.append(input4)
# Write to an output PDF document
merger.write(output_file)
output_file.close()
i += 1
回答1:
Resurrecting a super old question but ran into this and wanted to answer to hopefully prevent others from pasting your partial code above and running into the same problem.
Without seeing the rest I'm only guessing, but your loop doesn't create a new merger
, it just keeps appending and appending and appending, which is what you're reporting as the issue. I expect if you bring your merger initialization code into the loop (so that it gets re-setup each iteration) you'll have what you're looking for.
来源:https://stackoverflow.com/questions/28782845/using-pypdf2-to-merge-files-into-multiple-output-files