2 回答

TA貢獻1775條經(jīng)驗 獲得超11個贊
df
如果詳細(xì)信息是“csv”或“xlsx”,您只需創(chuàng)建一個名為 的對象。如果他們有另一種類型,則不會df
創(chuàng)建。因此,您不能在函數(shù)結(jié)束時返回 df。每當(dāng)您嘗試時,它都會崩潰。
有兩種可能性:
僅當(dāng) df 存在時才返回它,方法是將它從 if-elif 塊中返回。
如果文件類型無效,則創(chuàng)建一個沒有任何值的 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對于這兩個選項,如果類型不受支持,函數(shù)將返回。

TA貢獻1807條經(jīng)驗 獲得超9個贊
您應(yīng)該在任何條件之前初始化空變量,如下所示
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
添加回答
舉報