-1

I'm learning python and I would like to iterate a lot of files that are no consecutives in the enumeration. For example, the name of my files that I need to merge:

dp_1.pdf  I need it to merge with support_dp_1.pdf
dp_3.pdf - - - - - - - - - - - -  support_dp_3.pdf
ip_1.pdf - - - - - - - - - - - -  support_ip_1.pdf
ip_2.pdf - - - - - - - - - - - -  support_ip_2.pdf
ip_3.pdf - - - - - - - - - - - -  support_ip_3.pdf
ep_4.pdf - - - - - - - - - - - -  support_ep_4.pdf

My script is this:

from PyPDF2 import PdfFileMerger

files = ['dp_', 'ep_', 'ip_']
number = 1
while number <= 4:
        for f in files:
                pdfs = [f + str(number) + ".pdf", "support_" + f + str(number) + ".pdf"]
                name_file_output = "output_" + f + str(number) + ".pdf"
                fusion = PdfFileMerger()

                for pdf in pdfs:
                    fusion.append(open(pdf, 'rb'))

                with open(name_file_output, 'wb') as output:
                    fusion.write(output)

        number += 1

And I have this error:

FileNotFoundError: [Errno 2] No such file or directory: 'dp_2.pdf'

And the program exit. How can I iterate without exit and continue with the next files in the loop?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
  • 1
    Well, were you *expecting* the file `dp_2.pdf` to exist? Why or why not? If you were, and it isn't there, what happened when you tried to figure out why it isn't there? If you need to be able to handle the situation, what happened when you tried putting `python check if file exists` into a search engine? – Karl Knechtel Jun 24 '21 at 19:49

2 Answers2

1

You can use the os.path.exists function to check if the file exists before trying to merge it:

from PyPDF2 import PdfFileMerger
import os

files = ['dp_', 'ep_', 'ip_']
number = 1
while number <= 4:
    for f in files:
        pdfs = [f + str(number) + ".pdf", "support_" + f + str(number) + ".pdf"]
        name_file_output = "output_" + f + str(number) + ".pdf"
        fusion = PdfFileMerger()
        
        if not any(os.path.exists(pdf) for pdf in pdfs):
            continue
        
        for pdf in pdfs:
            fusion.append(open(pdf, 'rb'))

        with open(name_file_output, 'wb') as output:
            fusion.write(output)

    number += 1
not_speshal
  • 22,093
  • 2
  • 15
  • 30
0

Try adding this into your script

import pathlib

file = pathlib.Path("<filename>")
if file.exists():
stefan_aus_hannover
  • 1,777
  • 12
  • 13