Python PDF Randomizer Positional Argument Error

Question:

My python skills are very rusty and I’m trying to use python to randomize a pdf file for work. I know this has been discussed in other threads, I’ve been reading them and still can’t figure out what I’m doing wrong. I’ve been testing the code and everything else seems to be working correctly aside from output in line 43. If you could point me to where this has been answered or provide some help it would be greatly appreciated.

Line 43 (output =…) is throwing me this error message: TypeError: init() takes 1 positional argument but 2 were given.

Here’s the section causing issues.

42 output = PdfFileWriter(filePaths[0]+’-mixed.pdf’)

43 input1 = PdfFileReader(filePaths[0],"rb")

Full Code

#!/usr/bin/python
import os
import sys
import random

from PyPDF2 import PdfFileWriter, PdfFileReader


#Select  files with a dialog
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.call('wm', 'attributes', '.', '-topmost', True)
files = filedialog.askopenfilename(multiple=False) 

var = root.tk.splitlist(files)
filePaths = []
for f in var:
    filePaths.append(f)

print("The files selected are:")
print(filePaths)


if len(filePaths) == 0:
    print("Select a file!")
    exit(1)
    
# read input pdf and instantiate output pdf
output = PdfFileWriter(filePaths[0]+'-mixed.pdf')
input1 = PdfFileReader(filePaths[0],"rb")

# construct and shuffle page number list
pages = list(range(input1.getNumPages()))
random.shuffle(pages)

# display new sequence
print('Reordering pages according to sequence:')
print(pages)

# add the new sequence of pages to output pdf
for page in pages:
    output.addPage(input1.getPage(page))

# write the output pdf to file
outputStream = filePaths[0]+'-mixed.pdf','wb')
output.write(outputStream)
outputStream.close()
Asked By: Brian Booth

||

Answers:

The PdfFileWriter constructor takes no arguments, but you are supplying one.

The idea of that object is to construct a writer, add pages and other items to it, and then write it out using the write() method:

output = PdfFileWriter()

for page in pages:
    output.addPage(input1.getPage(page))

with open(filePaths[0]+'-mixed.pdf','wb') as outputStream:
    output.write(outputStream)
Answered By: mhawke
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.