繁体   English   中英

如何修复 UnboundLocalError:在 Python 中分配之前引用的局部变量“df”

[英]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。 无论何时尝试,它都会崩溃。

有两种可能:

  • 仅当它存在时才返回 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

使用这两个选项,如果类型不受支持,function 将返回None

您应该在任何条件之前初始化空变量,如下所示

  • 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM