[英]Opening Files with Loop in Python/SPSS
這是我第一次使用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
在每個文件並標記每個值要么school1
, school2
,或school3
,根據文件名
如果您有任何建議/問題,請告訴我。 謝謝
更新:我最終得到了這個:
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 ...”或使用正斜杠。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.