首页 > 解决方案 > 赋值之前引用的局部变量,但不是

问题描述

        # 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")

我越来越

local variable 'webp_path' referenced before assignment

如果我放全局,它说 webp_path 不存在

标签: pythonpython-3.x

解决方案


您收到错误是因为您尝试web_path在代码中访问,但是 web_path 在您的 for 循环中的 if 块下被初始化。
所以它可能永远不会被初始化。此外,可以有多个以 .webp 结尾的文件,因此我建议将图像转换逻辑保留在 for 循环下。这将修复您的代码:

       # 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")

推荐阅读