Python in SPSS - KEEP variables
<p>I have selected the variables I need based on a string within the variable name. I'm not sure how to keep only these variables from my SPSS file. </p>

<pre><code>begin program.
import spss,spssaux
spssaux.OpenDataFile(r'XXXX.sav')
target_string = 'qb2'
variables = [var for var in spssaux.GetVariableNamesList() if target_string in var]
vars = spssaux.VariableDict().expand(variables)
nvars=len(vars)
for i in range(nvars):
    print vars[i]
spss.Submit(r"""
SAVE OUTFILE='XXXX_reduced.sav'.
ADD FILES FILE=* /KEEP \n %s.
""" %(vars))
end program.
</code></pre>

<p>The list of variables that it prints out is correct, but it's falling over trying to KEEP them. I'm guessing it's something to do with not activating a dataset or bringing in the file again as to why there's errors?</p>

<p>It appears that the problem has been solved, but I would like to point out another solution that can be done without writing any Python code.  The extension command SPSSINC SELECT VARIABLES defines a macro based on properties of the variables.  This can be used in the ADD FILES command.  </p>

<p>SPSSINC SELECT VARIABLES MACRONAME="!selected" 
/PROPERTIES  PATTERN = ".*qb2".<br>
ADD FILES /FILE=* /KEEP !selected.  </p>

<p>The SELECT VARIABLES command is actually implemented in Python.  Its selection criteria can also include other metadata such as type and measurement level.</p>

python spss