在Python/SPSS中使用循环打开文件

0 投票
2 回答
954 浏览
提问于 2025-04-18 03:56

这是我第一次用Python和SPSS一起工作。我希望能在同一个文件夹里处理几个文件,创建一个新变量,然后保存这个文件。目前我写的代码是:

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

我希望这段代码能打开每个文件(比如school12014.sav、school22014.sav、school32014.sav),然后在每个文件里创建一个叫做school的变量,并根据文件名给每个值标记为school1school2school3

如果你有任何建议或问题,请告诉我。谢谢!

2 个回答

1

记住,反斜杠(\)是一个转义符,所以比如说,\t 会被转换成一个制表符(也就是Tab键的效果)。你可以在路径前面加上 r(表示原始字符串),像这样 r"c:\temp...",或者直接使用正斜杠(/)。

1

更新:我最后选择了这个:

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.

撰写回答