亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何修復 UnboundLocalError:在 Python 中賦值之前引用局部變量“df”

如何修復 UnboundLocalError:在 Python 中賦值之前引用局部變量“df”

米脂 2023-03-22 16:45:29
我正在溝通,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我的代碼可能有什么問題?
查看完整描述

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對于這兩個選項,如果類型不受支持,函數將返回。


查看完整回答
反對 回復 2023-03-22
?
函數式編程

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


查看完整回答
反對 回復 2023-03-22
  • 2 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號