0
        # Get .webpfile
        for file in os.listdir(selected_folder):
            if file.endswith(".webp"):
                webp_path = os.path.join(selected_folder, file)
                webp_name = os.path.join(file)
                


        # Convert .webp to .jpg because YouTube doesn't like .webp :/
        im = Image.open(webp_path).convert("RGB")
        im.save(webp_path + ".jpg","jpeg")

I'm getting

local variable 'webp_path' referenced before assignment

and if I put global, it says that webp_path doesn't exist

2
  • 1
    webp_path only exists if your if condition is true. It likely isn't, meaning it is being referenced before assignment. Commented Jul 25, 2021 at 16:41
  • webp_path is defined only if certain conditions are met. But Image.open(webp_path) is executed regardless of whether it is defined or not. Hence the error Commented Jul 25, 2021 at 16:41

2 Answers 2

1

You are getting the error because you are trying to access web_path in your code, however web_path is getting initialized under the if-block in your for-loop.
So there can be a chance that it might never get initialized. Also, there can be more than one file that ends with .webp, so I'd suggest keeping the image conversion logic under the for-loop. This will fix your code:

       # Get .webpfile
        for file in os.listdir(selected_folder):
            if file.endswith(".webp"):
                webp_path = os.path.join(selected_folder, file)
                webp_name = os.path.join(file)
            else:
                continue
                
            # Convert .webp to .jpg because YouTube doesn't like .webp :/
            im = Image.open(webp_path).convert("RGB")
            im.save(webp_path + ".jpg","jpeg")
Sign up to request clarification or add additional context in comments.

Comments

0

It is happening because there web_path is defined in your conditions but when some condition is True only but your Image.open(webp_path) executing when there is not web_path also.

You can try this to resolve your problem:

for file in os.listdir(selected_folder):
    if file.endswith(".webp"):
        webp_path = os.path.join(selected_folder, file)
        webp_name = os.path.join(file)

if web_path:
    im = Image.open(webp_path).convert("RGB")
    im.save(webp_path + ".jpg","jpeg")

Or try-expect, if you don't need anything to do if that if condition don't met:

for file in os.listdir(selected_folder):
    if file.endswith(".webp"):
        webp_path = os.path.join(selected_folder, file)
        webp_name = os.path.join(file)
try:
    im = Image.open(webp_path).convert("RGB")
    im.save(webp_path + ".jpg","jpeg")
except:
    pass

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.