在Python/SP中用循环打开文件

2024-06-25 23:14:27 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我第一次在spss中使用python。我希望在同一个目录中循环使用一些文件,创建一个新变量,然后保存该文件。目前我拥有的是:

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的变量,并根据文件名为每个值加上school1school2或{}

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


Tags: 文件inimport目录forprogrambeginsav
2条回答

更新:我最终还是选择了这个:

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.

请记住\是转义符,因此,例如,\t将映射到制表符。在路径文字上使用r(raw),如r“c:\temp…”或使用正斜杠。在

相关问题 更多 >