from __future__ import with_statement # code in this file requires at least Python 2.5 and thus will not work with SPSS 14 or 15 import spss, spssaux import glob, time, os from spssaux import _smartquote from spssaux import u ok1600 = spssaux.getSpssVersion() >= [16,0,0] def applySyntaxToFiles(inputspec, syntax, outputdatadir=None, outputfiledir=None, logfile=None): """Apply a syntax file to each file matching inputspec, and optionally write output and data files. inputfilespec is a wildcard directory specification of data files to process. E.,g., "c:/mydata/*.sav" syntax is a filespec for a syntax file to execute via the INSERT command If outputdatadir is not None, each input file will be written to the specified data directory after processing. If outputfiledir is not None, the designated Viewer window will be written to that directory and closed after processing each input file. It will have the input data file name but with an spv or spo extension. If logfile is not None, a log of file progress will be written as a plain text file. Example: begin program. import spss, spssaux3 spssaux3.applySyntaxToFiles("c:/temp/parts/*.sav", "c:/temp/process.sps", outputdatadir="c:/temp2", logfile="c:/temp2/log.txt", outputfiledir="c:/temp2") end program. """ extension = ok1600 and ".spv" or ".spo" with Writelog(logfile) as log: log.write("start: apply %(syntax)s to %(inputspec)s" % locals()) for input in glob.glob(inputspec): log.write("Getting: %(input)s and running %(syntax)s" % locals()) spss.Submit("""GET FILE = "%(input)s". INSERT FILE= "%(syntax)s".""" % locals()) if outputdatadir: outname = outputdatadir + "/" + os.path.basename(input) log.write("Writing %(outname)s" % locals()) spss.Submit('SAVE OUTFILE="%s".' % outname) if outputfiledir: outputname = outputfiledir + "/" + os.path.splitext(os.path.basename(input))[0] + extension log.write("Writing %s" % outputname) spss.Submit('OUTPUT SAVE NAME=* OUTFILE="%s".' % outputname) spss.Submit("OUTPUT CLOSE *.") class Writelog(object): """Manage a log file""" def __init__(self, logfile): self.logfile = logfile if self. logfile: self.file = file(logfile, "wb") def __enter__(self): return self def write(self, text): if self.logfile: self.file.write(time.asctime() + ": " + text + "\n") def close(self): if self.logfile: self.file.write(time.asctime() + ": Closing log" + "\n") self.file.close() def __exit__(self, type, value, tb): """cleanup for use with with statement""" self.close() return False