python - 赋值之前引用的局部变量,但不是
问题描述
# 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 不存在
解决方案
您收到错误是因为您尝试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")
推荐阅读
- vue.js - 如何将 axios 全局导入到 vue.js 项目中
- django - Django select option - displaying image in template
- spring-security - Communication between two microservices in JHipster using JWT
- sql - Query to display student_no, prj_name and prj_dur
- c++ - 如何制作arduino串行循环(连续接收数字)
- vim - How to match the white space between two strings in vim?
- java - ListView crashes
- ios - iOS Simulator connection timed out
- python-3.x - PySide2 and pyinstaller gui application won't run on certain windows computers
- r - Get object and indices from subsetting call