2 回答
TA贡献1775条经验 获得超11个赞
df
如果详细信息是“csv”或“xlsx”,您只需创建一个名为 的对象。如果他们有另一种类型,则不会df
创建。因此,您不能在函数结束时返回 df。每当您尝试时,它都会崩溃。
有两种可能性:
仅当 df 存在时才返回它,方法是将它从 if-elif 块中返回。
如果文件类型无效,则创建一个没有任何值的 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
None对于这两个选项,如果类型不受支持,函数将返回。
TA贡献1807条经验 获得超9个赞
您应该在任何条件之前初始化空变量,如下所示
df = ''
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
添加回答
举报