简体   繁体   中英

How to run python on multiple folder to create pdf?

The following code is to combine multiple images into one pdf. I am trying to run this code on multiple folder where each folder has several images as result, each folder will has one pdf.

import os
from PIL import Image
from fpdf import FPDF


pdf = FPDF()
sdir = "imageFolder/"
w,h = 0,0

for i in range(1, 100):
    fname = sdir + "IMG%.3d.png" % i
    if os.path.exists(fname):
        if i == 1:
            cover = Image.open(fname)
            w,h = cover.size
            pdf = FPDF(unit = "pt", format = [w,h])
        image = fname
        pdf.add_page()
        pdf.image(image,0,0,w,h)
    else:
        print("File not found:", fname)
    print("processed %d" % i)
pdf.output("output.pdf", "F")
print("done")

I was thinking to create another loop to bring the folder path which will come before the first loop:

   For j in range(1 to 70):
folderP=sdir+folder%1

And loop in each folder

Sorry I am still learning python. Any suggestion would be great!

You can use glob to get the paths of all pdfs and add them to a list, then you just iterate through the list and you wouldn't even need to check if they exist:

from glob import glob

sDir = 'imageFolder/'
pdfPaths = []

pdfPaths.extend(glob(f'{sDir}**/*.pdf', recursive=True))

for pdf in pdfPaths:
    # do stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM