My python merge PDF is not working

Asked

Viewed 24 times

-1

He’s showing error on line 3, says the file can’t be found, but I checked it all right, what can it be?

import PyPDF2

f1 = open('documento1.pdf', 'rb')
f2 = open('documento2.pdf', 'rb')

pdf1 = PyPDF2.PdfFileReader(f1)
pdf2 = PyPDF2.PdfFileReader(f2)

pdf1_pages = pdf1.getNumPages()
pdf2_pages = pdf2.getNumPages()

output_file = open('newpdf.pdf', 'wb')
writer = PyPDF2.PdfFileWriter

for i in range(pdf1_pages):
    writer.addPage(pdf1.getPage(i))

for i in range(pdf2_pages):
    writer.addPag()e(pdf2.getPage(i))

writer.write(output_file)

f1.close()
f2.close()
output_file.close

1 answer

1

When pgm Python generates an error of the type below, it means that the file cannot be found, i.e., the file is not where the program thinks it is.

raise IOError("%s not found." % path)
OSError: nome-do-arquivo.txt not found.

imagine the structure below:

projeto
   |
   +--- src
         |
         +--- meu-programa.py
         +--- um-arquivo.pdf

and meu-programa.py contain

f = open('um-arquivo.pdf', 'rb')
f.close()

If the meu-programa.py run inside the directory projeto/src, with the command python meu-programa.py, it will rotate normally.

However if it is executed from within projeto with python src/meu-programa.py it will generate the above error.

Thus, two paths to this example:

  1. Run from within projeto/src
  2. Specify the absolute path of the pdf as below
f = open('/projeto/src/um-arquivo.pdf')

The method path, module os helps a lot in this matter of file localization and directory structure with . (See here)

I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.