简体   繁体   中英

How to fix UnboundLocalError: local variable 'df' referenced before assignment in Python

I am communicating with pysimplegui but I am having the UnboundLocalError within one of my functions.

Here is the 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

What could be wrong with my code?

You only create an object named df , if the details are either "csv" or "xlsx". If they have another type, no df will be created. Hence, you can not return df at the end of your function. It will crash, whenever you try.

There are two possibilities:

  • Return df only if it exists by returning it out of the if-elif-block.
  • Create a df without any values if the file type is invalid.

Option 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")
        

Option 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

With both options, the function will return None if the type is unsupported.

You should initialize the empty variable before any condition like the following

  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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