Question

This is my first time using python with spss. I am hoping to cycle through a handful of files in the same directory, create a new variable, and then save the file. Currently what I have is:

begin program.
import spss, spssaux
schools = ['school1', 'school2', 'school3']
for x in schools:
   spssaux.OpenDataFile("C:\...\" + x + "2014.sav")
   school = x
end program.

I was hoping this would open each file (school12014.sav, school22014.sav, school32014.sav), and then create a variable called school in each file and label every value either school1, school2, or school3, depending on the file name

Let me know if you have any suggestions/questions. Thanks

Était-ce utile?

La solution 2

Update: I ended up going with this:

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

   #creates the variable
   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()


   spss.Submit("""save outfile="%s".""" % filename)

end program.

Autres conseils

Remember that \ is an escape leadin so, e.g., \t would be mapped into a tab character. Either use r (raw) on your path literals as in r"c:\temp..." or use forward slashes.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top