Skip to content
Advertisement

Assign multiple variables from a list of file names

I have a list of file

file_names=['file1.sav', 'file2.sav']

and a list of variables names

var_names=['var1', 'var2']

I want to assign every item in var_names a read_spss function.

so that ill get

var1= pd.read_spss('file1.sav')
var2= pd.read_spss('file2.sav')

Thanks

Advertisement

Answer

Like the comment above the easiest way to do this is with a dictionary.

#create empty dictionary
files = {}

file_names=['file1.sav', 'file2.sav']
var_names=['var1', 'var2']

#loop over both file_names and var_names and use them to build the dictionary
for var_name, file in zip(var_names, file_names):
    files[var_name] = pd.read_spss(file)

That way then you can just access it like this files['var1'] to get the content of file1.sav1.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement