SPSS Tutorials

BASICS REGRESSION T-TEST ANOVA CORRELATION

Add Filenames to Files Before Merging

Question

"I'd like to merge a number of data files with the ADD FILES command. However, in the merged file I'd like to see which record came from which file. Is there an easy way to accomplish this?"

SPSS Python Syntax Example

begin program.
import os,spss
dir = 'd:/temp2' # Specify folder containing .sav files.
fils = sorted([fil for fil in os.listdir(dir) if fil.endswith(".sav")])
vallabCmd = '\n'.join(['add value labels source_file ' + str(num + 1) + '"%s".'%fil for num,fil in enumerate(fils)])
for num,fil in enumerate(fils):
    num += 1
    spss.Submit('''
get file '%(dir)s/%(fil)s'.
compute source_file=%(num)d.
%(vallabCmd)s
save outfile '%(dir)s/%(fil)s'.
'''%locals())
spss.Submit('new file.')
end program.

Description

Assumptions

Previous tutorial: SPSS with Python – Looping over Scatterplots

Next tutorial: Adjust String Lengths before Merging Files

Let me know what you think!

*Required field. Your comment will show up after approval from a moderator.

This tutorial has 13 comments