0

I have this code:

from PIL import Image

image1 = Image.open(r'1.jpeg')
im1 = image1.convert('RGB')
im1.save(r'1.pdf')

# Part 2
image1 = Image.open(r'2.jpeg')
im1 = image1.convert('RGB')
im1.save(r'2.pdf')

And I want to make sure that part 2 of the code will run even if the first file doesn't exist, how can I do that?

ecm
  • 2,583
  • 4
  • 21
  • 29
LiON
  • 3
  • 3
  • 2
    perhaps a `try:` and `except:` block is what you are looking for? Here is a link that might help: https://docs.python.org/3/tutorial/errors.html – Party-with-Programming Sep 04 '21 at 07:05
  • 1
    If you "are a novice" then you should follow a tutorial from start to finish on the language basics first, and *then* think about using third-party libraries. – Karl Knechtel Sep 04 '21 at 07:17

2 Answers2

0

You could do that like so:

from PIL import Image

try:
    image1 = Image.open(r'1.jpeg')
    im1 = image1.convert('RGB')
    im1.save(r'1.pdf')
except OSError:
    print("first file doesn’t exist!")

image1 = Image.open(r'2.jpeg')
im1 = image1.convert('RGB')
im1.save(r'2.pdf')

To read more about try-except read here: https://docs.python.org/3/tutorial/errors.html

Eladtopaz
  • 1,036
  • 1
  • 6
  • 21
0

You can check if the pass to the image exists and then proceed accordingly.

from PIL import Image
import os.path

imgPath = "1.jpeg"
if os.path.isfile(imgPath) :
    image1 = Image.open(r'1.jpeg')
    im1 = image1.convert('RGB')
    im1.save(r'1.pdf')
else:
    image1 = Image.open(r'2.jpeg')
    im1 = image1.convert('RGB')
    im1.save(r'2.pdf')
vnk
  • 1,060
  • 1
  • 6
  • 18