![](/img/trans.png)
[英]UnboundLocalError: local variable 'df' referenced before assignment
[英]How to fix UnboundLocalError: local variable 'df' referenced before assignment in Python
我正在与pysimplegui
通信,但我的一个函数中有UnboundLocalError
。
这是function
:
def load_file(file):
file_details = file.split('.')
if file_details[1] == "csv":
df = pd.read_csv(file)
elif file_details[1] == "xlsx":
df = pd.read_excel(file)
elif file_details[1] != "csv" and file_details[1] != "xlsx":
sg.popup("Unsupported file type")
else:
sg.popup("Your file does not meet the requirements", "Please check the file requirements for more info")
return df
我的代码可能有什么问题?
如果详细信息是“csv”或“xlsx”,您只需创建一个名为df
的 object。 如果它们有其他类型,则不会创建df
。 因此,您不能在 function 的末尾返回 df。 无论何时尝试,它都会崩溃。
有两种可能:
选项1:
def load_file(file):
file_details = file.split('.')
if file_details[1] == "csv":
df = pd.read_csv(file)
return df
elif file_details[1] == "xlsx":
df = pd.read_excel(file)
return df
elif file_details[1] != "csv" and file_details[1] != "xlsx":
sg.popup("Unsupported file type")
else:
sg.popup("Your file does not meet the requirements", "Please check the file requirements for more info")
选项 2
def load_file(file):
file_details = file.split('.')
if file_details[1] == "csv":
df = pd.read_csv(file)
elif file_details[1] == "xlsx":
df = pd.read_excel(file)
elif file_details[1] != "csv" and file_details[1] != "xlsx":
sg.popup("Unsupported file type")
df = None
else:
sg.popup("Your file does not meet the requirements", "Please check the file requirements for more info")
df = None
return df
使用这两个选项,如果类型不受支持,function 将返回None
。
您应该在任何条件之前初始化空变量,如下所示
def load_file(file): file_details = file.split('.')
**df = ''**
if file_details[1] == "csv":
df = pd.read_csv(file)
elif file_details[1] == "xlsx":
df = pd.read_excel(file)
elif file_details[1] != "csv" and file_details[1] != "xlsx":
sg.popup("Unsupported file type")
else:
sg.popup("Your file does not meet the requirements", "Please check the file requirements for more info")
return df
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.