Python Functions: Pass parameter as string and reference?

I have a knot in my head. I wasn’t even sure what to google for. (Or how to formulate my title)

I want to do the following: I want to write a function that takes a term that occurs in the name of a .csv, but at the same time I want a df to be named after it.

Like so:

def read_data_into_df(name):
     df_{name} = pd.read_csv(f"file_{name}.csv")

Of course the df_{name} part is not working. But I hope you get the idea.

Is this possible without hard coding?


>Solution :

IIUC, you can use globals :

def read_data_into_df(name):
     globals()[f"df_{name}"] = pd.read_csv(f"file_{name}.csv")

Leave a Reply