Question

Ok so I've been playing with python and spss to achieve almost what I want. I am able to open the file and make the changes, however I am having trouble saving the files (and those changes). What I have (using only one school in the schoollist):

begin program.
import spss, spssaux
import os
schoollist = ['brow']
for x in schoollist:
   school = 'brow'
   school2 = school + '06.sav'
   filename = os.path.join("Y:\...\Data", school2) #In this instance, Y:\...\Data\brow06.sav
   spssaux.OpenDataFile(filename)

   #--This block are the changes and not particularly relevant to the question--#
   cur=spss.Cursor(accessType='w')
   cur.SetVarNameAndType(['name'],[8])
   cur.CommitDictionary()
   for i in range(cur.GetCaseCount()):
      cur.fetchone()
      cur.SetValueChar('name', school)
      cur.CommitCase()
   cur.close()

   #-- What am I doing wrong here? --#
   spss.Submit("save outfile = filename".)

end program.

Any suggestions on how to get the save outfile to work with the loop? Thanks. Cheers

Était-ce utile?

La solution

In your save call, you are not resolving filename to its actual value. It should be something like this: spss.Submit("""save outfile="%s".""" % filename)

Autres conseils

I'm unfamiliar with spssaux.OpenDataFile and can't find any documentation on it (besides references to working with SPSS data files in unicode mode). But what I am going to guess is the problem is that it grabs the SPSS data file for use in the Python program block, but it isn't actually opened to further submit commands.

Here I make a test case that instead of using spssaux.OpenDataFile to grab the file, does it all with SPSS commands and just inserts the necessary parts via python. So first lets create some fake data to work with.

*Prepping the example data files.
FILE HANDLE save /NAME = 'C:\Users\andrew.wheeler\Desktop\TestPython'.
DATA LIST FREE / A .
BEGIN DATA
1
2
3
END DATA.

SAVE OUTFILE = "save\Test1.sav".
SAVE OUTFILE = "save\Test2.sav".
SAVE OUTFILE = "save\Test3.sav".
DATASET CLOSE ALL.

Now here is a paired down version of what your code is doing. I have the LIST ALL. command inserted in so you can check the output that it is adding the variable of interest to the file.

*Sequential opening the data files and appending data name.
BEGIN PROGRAM.
import spss
import os
schoollist = ['1','2','3']
for x in schoollist:
  school2 = 'Test' + x + '.sav'
  filename = os.path.join("C:\\Users\\andrew.wheeler\\Desktop\\TestPython", school2)
  #opens the SPSS file and makes a new variable for the school name
  spss.Submit("""
GET FILE = "%s".
STRING Name (A20).
COMPUTE Name = "%s".
LIST ALL.
SAVE OUTFILE = "%s".
""" %(filename, x,filename))
END PROGRAM.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top