Conversion of PDF images with Python

Asked

Viewed 70 times

0

I am trying to convert all images from a directory into a single PDF. However I am having difficulties.

When I run my system it gives the error below, it tries to read the file . py also.

from PIL import Image
import os
filepath = os.getcwd()

for p in os.listdir(filepath):

    filename = filepath+'\\'+p

    im = Image.open(filename)

    if im.mode == "RGB":
        im = im.convert("RGB")
    new_file = "novo.pdf"
    new_filename = os.getcwd()
    file = new_filename+"\\"+new_file
    if not os.path.exists(new_filename):
        im.save(file, "PDF")
Traceback (most recent call last): 
 File "C:/crl/pdf/teste.py", line 9, 
   in <module> im = Image.open(filename) 
 File "C:\Users\willian.angelo\anaconda3\lib\site-packages\PIL\Image.py", line 2687, 
   in open % (filename if filename else fp)) OSError: cannot identify image file 'C:\\crl\\pdf\\teste.py'
  • Dude, put the mistake that’s happening. What’s your doubt, because it’s too vague

  • I’m sorry I forgot to put the error!

  • Traceback (Most recent call last): File "C:/crl/pdf/teste.py", line 9, in <module> im = Image.open(filename) File "C: Users Willian.Angelo anaconda3 lib site-Packages PIL Image.py", line 2687, in open % (filename filename Else Fp)) Oserror: cannot identify image file 'C: crl pdf teste.py'

  • that file . py is in the same directory as the images, you can remove the images to another directory

  • this file. py is the python scripit itself, I can even put the imgaens in another folder, however I want the scritp to run in the current directory, as I will add to the resources of the operating system, to be used quickly

1 answer

0

you can check if the file ends with .py and ignore it, using a condition with the function endswith class string. As example below. It would be one of the options.

from PIL import Image
import os
filepath = os.getcwd()

for p in os.listdir(filepath):
    if not str(p).endswith('.py'):

        filename = filepath+'\\'+p

        im = Image.open(filename)

        if im.mode == "RGB":
            im = im.convert("RGB")
        new_file = "novo.pdf"
        new_filename = os.getcwd()
        file = new_filename+"\\"+new_file
        if not os.path.exists(new_filename):
            im.save(file, "PDF")

Browser other questions tagged

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