### Install savReaderWriter using setup.py Source: https://pythonhosted.org/savReaderWriter/_sources/index.txt Install the savReaderWriter package by running the setup.py script. ```sh python setup.py install ``` -------------------------------- ### Install bleeding-edge savReaderWriter from repository Source: https://pythonhosted.org/savReaderWriter/index.html Install the latest development version of savReaderWriter directly from its Bitbucket repository. ```bash pip install -U -e git+https://bitbucket.org/fomcl/savreaderwriter.git#egg=savreaderwriter ``` -------------------------------- ### Example of Value Labels Structure Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Demonstrates the dictionary structure for setting and getting value labels for both numeric and string variables. ```python { b'numGender': {1: b'female', {2: b'male'}}, b'strGender': {b'f': b'female', b'm': b'male'}} ``` -------------------------------- ### Setting and Getting Locale on macOS Source: https://pythonhosted.org/savReaderWriter/_static/mac_os_x_locale_quirks.txt Demonstrates setting the locale to the system default and then attempting to retrieve it. This example highlights a common ValueError on macOS when the locale name is not recognized. ```python import locale locale.setlocale(locale.LC_ALL, "") locale.getlocale() ``` -------------------------------- ### Install savReaderWriter using pip Source: https://pythonhosted.org/savReaderWriter/index.html Install the savReaderWriter package using pip for easy integration. ```bash pip install savReaderWriter ``` -------------------------------- ### Install cWriterow Package Source: https://pythonhosted.org/savReaderWriter/index.html Install the cWriterow package for a faster Cython implementation of pyWriterow. Requires Cython and running setup.py. ```bash easy_install cython python setup.py build_ext --inplace ``` -------------------------------- ### File Attributes Example Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Demonstrates the structure of file attributes, including attribute names, values, and revision dates. Attribute arrays are indicated by square brackets and must start with index 1. ```python b'attrName[1]': b'attrValue1', b'revision[1]': b'2010-10-09', b'revision[2]': b'2010-10-22', b'revision[3]': b'2010-11-19' ``` -------------------------------- ### Install savReaderWriter using pip Source: https://pythonhosted.org/savReaderWriter/_sources/index.txt Install the savReaderWriter package using pip. For the latest development version, use the Git repository. ```sh pip install savReaderWriter ``` ```sh pip install -U -e git+https://bitbucket.org/fomcl/savreaderwriter.git#egg=savreaderwriter ``` -------------------------------- ### Example of Variable Attributes Structure Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Illustrates the nested dictionary structure for setting and getting custom variable attributes, mapping variable names to dictionaries of attribute names and values. ```python { b'var1': {b'attr name x': b'attr value x', b'attr name y': b'attr value y'}, b'var2': {b'attr name a': b'attr value a', b'attr name b': b'attr value b'}} ``` -------------------------------- ### Get a specific record by key using an ID variable Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savReader.html Instantiate SavReader with a file path and an 'idVar'. Use the get() method with a key to retrieve a record, providing a default value if the key is not found. This method uses binary search for efficiency. ```python data = SavReader(savFileName, idVar="ssn") data.get("987654321", "social security number not found!") data.close() ``` -------------------------------- ### Example of Missing Values Structure Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Provides a comprehensive example of the dictionary structure for defining user-defined missing values, including discrete values, ranges, and string values. ```python # note that 'lower', 'upper', 'value(s)' are without b' prefix missingValues = { # discrete values b"someNumvar1": {"values": [999, -1, -2]}, # range, cf. MISSING VALUES x (-9 THRU -1) b"someNumvar2": {"lower": -9, "upper": -1}, b"someNumvar3": {"lower": -9, "upper": -1, "value": 999}, # string variables can have up to three missing values b"someStrvar1": {"values": [b"foo", b"bar", b"baz"]}, b"someStrvar2": {"values': b"bletch"} } ``` -------------------------------- ### savReaderWriter.SavReader.getSavFileInfo Source: https://pythonhosted.org/savReaderWriter/genindex.html Gets general file information from a SavReader object. ```APIDOC ## getSavFileInfo() ### Description Retrieves general information about the .sav file. ### Method N/A (Method call) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response - **sav_file_info** (dict) - Information about the .sav file. ``` -------------------------------- ### Set DEW and GUID Information Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Sets Data Entry (DEW) and GUID information in a SAV file. Includes byte swapping logic if specified and handles writing data in segments. ```python data, asciiGUID = info["data"], info["GUID"] # input validation is_ascii = all(map(lambda x: ord(x) < 128, asciiGUID)) if not isinstance(asciiGUID, str) and is_ascii: raise ValueError("GUID must be a string of ascii characters") # I am not sure at all about the following swapit = info.has_key("swapBytes") and info.get("swapBytes") def swap(x): """swap bytes if needed""" src_fmt = '<%s' if sys.byteorder == 'little' else '>%s' dst_fmt = ">%s" if swapit and src_fmt[0] == "<" else "<%s" if isinstance(x, (float, int)): src_fmt, dst_fmt = src_fmt % "l", dst_mft % "l" elif isinstance(x, str): src_fmt, dst_fmt = src_fmt % "s", dst_mft % "s" else: type_ = re.search("'(\\w+)'", str(type(x))).group(1) raise TypeError("Must be str, int or float, not %s") % type_ if src_fmt != dst_fmt: x = struct.unpack(dst_fmt, struct.pack(src_fmt, x))[0] return x if swapit: data, asciiGUID = map(swap, data), swap(asciiGUID) # write DEW information for i, pData in enumerate(data): nBytes = len(pData) args = c_int(self.fh), c_void_p(pData), c_long(nBytes) # ... first segment if not i: func = self.spssio.spssSetDEWFirst retcode = func(*args) # ... subsequent segments else: func = self.spssio.spssSetDEWNext retcode = func(*args) if retcode > 0: break # write GUI information if not retcode: args = self.fh, c_char_py3k(asciiGUID) func = self.spssio.spssSetDEWGUID func.argtypes = [c_int, c_char_p] retcode = func(*args) if retcode: msg = "Problem setting Data Entry info with function %r" checkErrsWarns(msg % func.__name__, retcode) ``` -------------------------------- ### Get System String Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/generic.html Retrieves the name of the system under which the SPSS file was created as a string. ```python sysName = create_string_buffer(42) func = self.spssio.spssGetSystemString retcode = func(c_int(self.fh), byref(sysName)) checkErrsWarns("Problem getting SystemString", retcode) return sysName.value ``` -------------------------------- ### textInfo Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Get or set text information. This method takes a savFileName and returns a string containing file build information. ```APIDOC ## textInfo ### Description Get/Set text information. Takes a savFileName and returns a string of the form: “File %r built using SavReaderWriter.py version %s (%s)”. This is akin to, but _not_ equivalent to the SPSS syntax command DISPLAY DOCUMENTS ``` -------------------------------- ### Example of Variable Labels Structure Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Illustrates the dictionary format for setting and retrieving variable labels, mapping variable names to their descriptive labels. ```python { b'salary': b'Salary (dollars)', b'educ': b'Educational level (years)'} ``` -------------------------------- ### savReaderWriter.SavReader.getHeader Source: https://pythonhosted.org/savReaderWriter/genindex.html Gets the header information from a SavReader object. ```APIDOC ## getHeader() ### Description Retrieves the header information of the .sav file. ### Method N/A (Method call) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response - **header_info** (Header) - The header object. ``` -------------------------------- ### Example of Variable Sets Structure Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Demonstrates the dictionary format for defining and retrieving variable sets, where keys are set names and values are lists of associated variables. ```python { b'SALARY': [b'salbegin', b'salary'], b'DEMOGR': [b'gender', b'minority', b'educ']} ``` -------------------------------- ### Example of Formats Structure Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Shows the dictionary structure for managing print and write formats for variables, mapping variable names to SPSS format strings. ```python { b'salary': b'DOLLAR8', b'gender': b'A1', b'educ': b'F8.2'} ``` -------------------------------- ### Retrieve all records from a SAV file Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savReader.html Instantiate SavReader with a file path and use the all() method to get a list of all records. Ensure the file is closed after use. ```python data = SavReader("someFile.sav") list_of_lists = data.all() data.close() ``` -------------------------------- ### Get Data Entry Information Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Retrieves information private to the Data Entry for Windows (DEW) product. This includes DEW segments and a globally unique identifier (GUID). ```APIDOC ## dataEntryInfo ### Description Gets information private to the Data Entry for Windows (DEW) product. ### Method `dataEntryInfo` (getter) ### Parameters None ### Response - **dataEntryInfo** (dictionary) - A dictionary containing DEW information. - `"data"` (list): A list of DEW segments. - `"GUID"` (string): The globally unique identifier. Returns an empty dictionary if the file contains no DEW information. ### Response Example ```json { "data": [ "", "" ], "GUID": "" } ``` ### Remarks - This method checks for byte order differences between the host and file systems and raises a `ValueError` if they differ. - DEW information is not copied when using mode="cp" in the SavWriter initializer. - This feature is entirely untested. ``` -------------------------------- ### Launch savViewer utility Source: https://pythonhosted.org/savReaderWriter/index.html Launch the savViewer utility, a PyQt4-based script for viewing various data file formats including .sav, .zsav, .xls, .xlsx, .csv, and .tab. ```bash python -m savReaderWriter.util.savViewer ``` -------------------------------- ### Initialize SavWriter and Write Records Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savWriter.html Demonstrates the typical usage of SavWriter to create a new .sav file, define variable names and types, and write records row by row. Ensure the file path and variable definitions are correct before instantiation. ```python records = [[b'Test1', 1, 1], [b'Test2', 2, 1]] varNames = [b'var1', b'v2', b'v3'] varTypes = {b'var1': 5, b'v2': 0, b'v3': 0} savFileName = 'someFile.sav' with SavWriter(savFileName, varNames, varTypes) as writer: for record in records: writer.writerow(record) ``` -------------------------------- ### Example SAV File Creation for Testing Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savReaderNp.html Creates a sample SAV file with numeric and datetime data for testing purposes. This snippet demonstrates how to use SavWriter to generate a test file, which can then be read by SavReaderNp. ```python import time from contextlib import closing savFileName = "./test_data/all_numeric_datetime_uncompressed.sav" kwargs = dict( \ savFileName = savFileName, varNames = ["v1", "v2"], varTypes = {"v1": 0, "v2": 0}, formats = {"v1": "DOLLAR15.2", "v2": "EDATE40"} ) if not os.path.exists(savFileName): with SavWriter(**kwargs) as writer: for i in xrange(10 ** 2): value = None if not i else 11654150400. writer.writerow([i, value]) ``` -------------------------------- ### Initialize SavReader with Options Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savReader.html Demonstrates typical usage of SavReader by opening a file and iterating through its records. Use this pattern for processing all data within an SPSS file. ```python with SavReader('somefile.sav', returnHeader=True) as reader: header = reader.next() for line in reader: process(line) ``` -------------------------------- ### Run SavViewer Utility Source: https://pythonhosted.org/savReaderWriter/_sources/index.txt Execute the SavViewer utility from the command line. You can run it without arguments to open a file dialog or provide a specific file path. ```sh python -m savReaderWriter.util.savViewer python -m savReaderWriter.util.savViewer '/path/to/some/file.sav' ``` -------------------------------- ### Launch savViewer with a specific file Source: https://pythonhosted.org/savReaderWriter/index.html Launch the savViewer utility and open a specific data file by providing its path as an argument. ```bash python -m savReaderWriter.util.savViewer '/path/to/some/file.sav' ``` -------------------------------- ### Context Manager Entry Point Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savWriter.html Enters the context manager, returning the writer object to enable 'writerow' and 'writerows' methods within a 'with' statement. ```python def __enter__(self): """This function returns the writer object itself so the writerow and writerows methods become available for use with 'with' statements""" return self ``` -------------------------------- ### Read and display the first five records Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savReader.html Instantiate SavReader with a file path and use the head() method to view the initial records. Ensure the file is closed after use. ```python data = SavReader("someFile.sav") print("The first five records look like this: %s" % data.head()) data.close() ``` -------------------------------- ### Get Variable Attributes Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Retrieves attributes for a specific variable. It involves two steps: first getting the size of the attribute array, then fetching the attributes with the correct size. Memory is freed after retrieval. ```python # step 1: get array size nAttr = c_int() retcode = func(self.fh, c_char_py3k(vName), byref(attrNamesArr), byref(attrValuesArr), byref(nAttr)) if retcode: msg = "Problem getting attributes of variable '%s' (step 1/2)" checkErrsWarns(msg % varName.decode(), retcode) # step 2: get attributes with arrays of proper size nAttr = c_int(nAttr.value) attrNamesArr = (POINTER(c_char_p * nAttr.value))() attrValuesArr = (POINTER(c_char_p * nAttr.value))() func.argtypes = [c_int, c_char_p, POINTER(POINTER(c_char_p * nAttr.value)), POINTER(POINTER(c_char_p * nAttr.value)), POINTER(c_int)] retcode = func(self.fh, c_char_py3k(vName), byref(attrNamesArr), byref(attrValuesArr), byref(nAttr)) if retcode: msg = "Problem getting attributes of variable '%s' (step 2/2)" checkErrsWarns(msg % varName.decode(), retcode) # get array contents if not nAttr.value: continue k, v, n = attrNamesArr[0], attrValuesArr[0], nAttr.value attribute = dict([(k[i], v[i]) for i in xrange(n)]) attributes[varName] = attribute # clean up args = (attrNamesArr, attrValuesArr, nAttr) self.freeMemory("spssFreeAttributes", *args) ``` -------------------------------- ### Get Concise File Report (Python 2) Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Illustrates how to get a concise report of the SPSS data file using the unicode representation of the SavReader object in Python 2. Ensure the file is closed after retrieving the report. ```python data = SavReader(savFileName) print(unicode(data)) # Python 3: str(data) data.close() ``` -------------------------------- ### SavHeaderReader Initialization and Usage Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savHeaderReader.html Demonstrates typical usage of SavHeaderReader within a context manager to access file metadata. Ensure the file is properly closed using 'with' or 'close()'. ```python with SavHeaderReader(savFileName) as header: metadata = header.all() report = str(header) print(metadata.varLabels) ``` -------------------------------- ### savReaderWriter.SavReader.getFileReport Source: https://pythonhosted.org/savReaderWriter/genindex.html Gets the file report from a SavReader object. ```APIDOC ## getFileReport() ### Description Retrieves a report about the .sav file. ### Method N/A (Method call) ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response - **file_report** (str) - The file report. ``` -------------------------------- ### __enter__ Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savWriter.html Enters a context manager, returning the writer object itself to enable the use of writerow and writerows methods within 'with' statements. ```APIDOC ## __enter__ ### Description Enters a context manager, returning the writer object itself to enable the use of writerow and writerows methods within 'with' statements. ### Method __enter__ ``` -------------------------------- ### SavReader.head() Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savReader.html Returns the first n records from the SAV file. ```APIDOC ## SavReader.head() ### Description This convenience function returns the first records. ### Parameters - **n** (int) - Optional - The number of records to return. Defaults to 5. ### Request Example ```python data = SavReader("someFile.sav") print("The first five records look like this: %s" % data.head()) data.close() ``` ``` -------------------------------- ### Get Number of Variables Property Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Returns the number of variables (columns) present in the SPSS dataset. ```python @property def numberofVariables(self): """This function returns the number of variables (columns) in the spss dataset ``` -------------------------------- ### fileAttributes Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Get or set DATAFILE ATTRIBUTES. This method returns or accepts a dictionary of file attributes. ```APIDOC ## fileAttributes ### Description Get/Set DATAFILE ATTRIBUTES. Returns/Takes a dictionary of the form: ``` b'attrName[1]': b'attrValue1', b'revision[1]': b'2010-10-09', b'revision[2]': b'2010-10-22', b'revision[3]': b'2010-11-19' ``` Square brackets indicate attribute arrays, which must start with 1. ``` -------------------------------- ### caseWeightVar Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Gets or sets the case weight variable for the SAV file. This variable is used for weighted analyses. ```APIDOC ## caseWeightVar ### Description Gets or sets the case weight variable for the SAV file. This variable is used for weighted analyses. ### Method GETTER/SETTER ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (Setter) - **varName** (string) - Required - The name of the variable to be set as the case weight variable. ### Request Example (Setter) ```python # Example of setting a case weight variable # Assuming 'my_sav_file' is an instance of the savReaderWriter header class my_sav_file.caseWeightVar = 'WeightVarName' ``` ### Response (Getter) #### Success Response (200) - **caseWeightVar** (string) - The name of the case weight variable, if any. #### Response Example (Getter) ```python # Example of getting the case weight variable # Assuming 'my_sav_file' is an instance of the savReaderWriter header class weight_var = my_sav_file.caseWeightVar print(weight_var) ``` ### Error Handling - Raises `SPSSIOError` if there is a problem getting the case weight variable name. ``` -------------------------------- ### SavHeaderReader Constructor Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savHeaderReader.html Initializes the SavHeaderReader with the specified file name and I/O options. It sets up internal variables by calling the parent class constructor and opening the SAV file. ```python def __init__(self, savFileName, ioUtf8=False, ioLocale=None): """ Constructor. Initializes all vars that can be recycled """ super(SavHeaderReader, self).__init__(savFileName, b"rb", None, ioUtf8, ioLocale) self.fh = self.openSavFile() self.varNames, self.varTypes = self.varNamesTypes self.numVars = self.numberofVariables self.nCases = self.numberofCases ``` -------------------------------- ### ioLocale Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/generic.html Gets or sets the I/O Module's locale, corresponding to the SPSS command SET LOCALE. ```APIDOC ## ioLocale ### Description This property gets/sets the I/O Module's locale. This corresponds with the SPSS command `SET LOCALE`. The I/O Module's locale is separate from that of the client application. The `` parameter and the return value are identical to those for the C run-time function setlocale. The exact locale name specification depends on the OS of the host system, but has the following form: `_.[@]` The 'codeset' and 'modifier' components are optional and in Windows, aliases (e.g. 'english') may be used. When the I/O Module is first loaded, its locale is set to the system default. ### See also - linux : ``_ - windows : ``_ ### Returns - The current locale name as a string. ``` -------------------------------- ### Variable Alignments Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Allows getting and setting the text alignment for variables. Valid alignments are 'left', 'right', and 'center'. ```APIDOC ## Variable Alignments ### Description Get or set the alignment of text within variable columns. Returns/Takes a dictionary of the form `{varName: alignment}`. Valid alignment values are: 'left', 'right', 'center'. ### Method `alignments` (property) ### Parameters #### Request Body (for setter) - **varAlignments** (dict) - Required - A dictionary where keys are variable names (string) and values are the desired alignments ('left', 'right', or 'center'). ### Request Example ```python # Get alignments aligns = sav_writer.alignments # Set alignments sav_writer.alignments = {'Age': 'right', 'Name': 'left'} ``` ### Response #### Success Response (200) - **alignments** (dict) - A dictionary mapping variable names to their alignment strings ('left', 'right', or 'center'). ``` -------------------------------- ### SavReader.head Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savReader.html Returns the first n records from the SAV file. ```APIDOC ## head(n=5) ### Description This convenience function returns the first records. ### Parameters - **n** (int) - Optional - The number of records to return. Defaults to 5. ``` -------------------------------- ### Write Records to SAV File Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Demonstrates the typical usage of SavWriter to create a .sav file and write records to it. Ensure the file is properly closed after writing. ```python records = [[b'Test1', 1, 1], [b'Test2', 2, 1]] varNames = [b'var1', b'v2', b'v3'] varTypes = {b'var1': 5, b'v2': 0, b'v3': 0} savFileName = 'someFile.sav' with SavWriter(savFileName, varNames, varTypes) as writer: for record in records: writer.writerow(record) ``` -------------------------------- ### caseWeightVar Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Get or set the WEIGHT variable. This method takes a valid varName and returns the weight variable, if any, as a string. ```APIDOC ## caseWeightVar ### Description Get/Set WEIGHT variable. Takes a valid varName, and returns weight variable, if any, as a string. ``` -------------------------------- ### Get All Records from SavReader Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Retrieve all records from a SavReader object as a list of lists. Ensure the SavReader is closed after use. ```python data = SavReader(savFileName) list_of_lists = data.all() data.close() ``` -------------------------------- ### SavWriter Constructor Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Initializes the SavWriter object. It can be used to create a new .sav file or copy an existing one with modifications. ```APIDOC ## SavWriter ### Description Constructor. Initializes all vars that can be recycled. ### Parameters - **_savFileName** (str) - The name of the .sav file to be created or written to. - **_varNames** (list) - A list of variable names. - **_varTypes** (dict) - A dictionary mapping variable names to their types. - **_valueLabels** (dict, optional) - Dictionary for value labels. - **_varLabels** (dict, optional) - Dictionary for variable labels. - **_formats** (dict, optional) - Dictionary for variable formats. - **_missingValues** (dict, optional) - Dictionary for missing values. - **_measureLevels** (dict, optional) - Dictionary for measure levels. - **_columnWidths** (dict, optional) - Dictionary for column widths. - **_alignments** (dict, optional) - Dictionary for alignments. - **_varSets** (dict, optional) - Dictionary for variable sets. - **_varRoles** (dict, optional) - Dictionary for variable roles. - **_varAttributes** (dict, optional) - Dictionary for variable attributes. - **_fileAttributes** (dict, optional) - Dictionary for file attributes. - **_fileLabel** (str, optional) - The file label. - **_multRespDefs** (dict, optional) - Dictionary for multiple response definitions. - **_caseWeightVar** (str, optional) - The case weight variable name. - **_overwrite** (bool, optional) - Whether to overwrite the file if it exists. Defaults to True. - **_ioUtf8** (bool, optional) - Whether to use UTF-8 encoding for I/O. Defaults to False. - **_ioLocale** (str, optional) - The I/O locale. - **_mode** (str, optional) - The mode of operation ('wb' for write binary, 'cp' for copy). Defaults to 'wb'. - **_refSavFileName** (str, optional) - Reference file name for header initialization (used with mode='cp'). ### Example ```python records = [[b'Test1', 1, 1], [b'Test2', 2, 1]] varNames = [b'var1', b'v2', b'v3'] varTypes = {b'var1': 5, b'v2': 0, b'v3': 0} savFileName = 'someFile.sav' with SavWriter(savFileName, varNames, varTypes) as writer: for record in records: writer.writerow(record) ``` ``` -------------------------------- ### Get SavReader Shape Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Retrieve the number of rows and columns from a SavReader object. Ensure the SavReader is closed after use. ```python data = SavReader(savFileName) data.shape.nrows == len(data) # True data.close() ``` -------------------------------- ### Get Variable Alignments Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Retrieves the alignment for each variable. Valid alignments are 'left', 'right', and 'center'. Errors during retrieval are logged. ```python @property @decode def alignments(self): """Get/Set `VARIABLE ALIGNMENT`. Returns/Takes a dictionary of the form `{varName: alignment}`. Valid alignment values are: "left", "right", "center". .. warning:: *measureLevels, columnWidths, alignments must all three be set, if used*""" func = self.spssio.spssGetVarAlignment func.argtypes = [c_int, c_char_p, POINTER(c_int)] alignments = {0: b"left", 1: b"right", 2: b"center"} alignment_ = c_int() varAlignments = {} for varName in self.varNames: vName = self.vNames[varName] retcode = func(self.fh, c_char_py3k(vName), alignment_) alignment = alignments[alignment_.value] varAlignments[varName] = alignment if retcode: msg = "Problem getting variable alignment: '%s'" checkErrsWarns(msg % varName.decode(), retcode) return varAlignments ``` -------------------------------- ### Load SPSSIO Libraries Based on Platform Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/generic.html Loads and returns the appropriate SPSSIO libraries based on the operating system and architecture (32-bit or 64-bit). It handles Windows, Linux (including zLinux), and macOS, calling _loadLibs to perform the actual library loading. ```python def loadLibrary(self): # pragma: no cover """This function loads and returns the SPSSIO libraries, depending on the platform.""" arch = platform.architecture()[0] is_32bit, is_64bit = arch == "32bit", arch == "64bit" pf = sys.platform.lower() # windows if pf.startswith("win") and is_32bit: spssio = self._loadLibs("win32") elif pf.startswith("win"): spssio = self._loadLibs("win64") # linux elif pf.startswith("lin") and is_32bit: spssio = self._loadLibs("lin32") elif pf.startswith("lin") and is_64bit and os.uname()[-1] == "s390x": # zLinux64: Thanks Anderson P. from System z Linux LinkedIn Group! spssio = self._loadLibs("zlinux") elif pf.startswith("lin") and is_64bit: spssio = self._loadLibs("lin64") ``` -------------------------------- ### Get Variable Labels Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Retrieves variable labels from the SAV file. It iterates through each variable name and fetches its corresponding label. ```python @property @decode def varLabels(self): """Get/set `VARIABLE LABELS`. Returns/takes a dictionary of the form `{varName: varLabel}`. For example: .. code-block:: python {b'salary': b'Salary (dollars)', b'educ': b'Educational level (years)'} """ lenBuff = MAXLENGTHS['SPSS_MAX_VARLABEL'][0] varLabel = create_string_buffer(lenBuff) func = self.spssio.spssGetVarLabelLong func.argtypes = [c_int, c_char_p, POINTER(c_char * lenBuff), c_int, POINTER(c_int)] varLabels = {} for varName in self.varNames: vName = self.vNames[varName] retcode = func(self.fh, c_char_py3k(vName), varLabel, lenBuff, c_int()) varLabels[varName] = varLabel.value if retcode: msg = "Problem getting variable label of variable %r" % varName checkErrsWarns(msg, retcode) return varLabels ``` -------------------------------- ### SavReader.all Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Returns all records from the SAV file as a list. ```APIDOC ## all ### Description This convenience function returns all the records. ### Example ```python data = SavReader("someFile.sav") list_of_lists = data.all() data.close() ``` ``` -------------------------------- ### Get Value Labels (String) Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Retrieves value labels for string variables. It determines the array size and then fetches the labels. ```python # step 1b: get array size (string values) else: valuesArr, labelsArr = initArrays(False) func = funcC func.argtypes = [c_int, c_char_p, POINTER(POINTER(c_char_p * 0)), POINTER(POINTER(c_char_p * 0)), POINTER(c_int)] retcode = func(self.fh, c_char_py3k(vName), valuesArr, labelsArr, numLabels) valuesArr, labelsArr = initArrays(False, numLabels.value) func.argtypes = [c_int, c_char_p, POINTER(POINTER(c_char_p * numLabels.value)), POINTER(POINTER(c_char_p * numLabels.value)), POINTER(c_int)] ``` -------------------------------- ### SavWriter Constructor Parameters Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savWriter.html Details the parameters available for the SavWriter constructor, including file name, variable information, metadata options, and file handling modes like overwrite, UTF-8 encoding, and reference file usage for copying. ```python def __init__(self, savFileName, varNames, varTypes, valueLabels=None, varLabels=None, formats=None, missingValues=None, measureLevels=None, columnWidths=None, alignments=None, varSets=None, varRoles=None, varAttributes=None, fileAttributes=None, fileLabel=None, multRespDefs=None, caseWeightVar=None, overwrite=True, ioUtf8=False, ioLocale=None, mode=b"wb", refSavFileName=None): """ Constructor. Initializes all vars that can be recycled """ super(Header, self).__init__(savFileName, ioUtf8, ioLocale) self.savFileName = savFileName self.varNames = self.encode(varNames) self.varTypes = self.encode(varTypes) self.overwrite = overwrite self.mode = mode self.refSavFileName = refSavFileName self.fh = super(Header, self).openSavFile(self.savFileName, self.mode, self.refSavFileName) self.myStruct = self.getStruct(self.varTypes, self.varNames, self.mode) self.pack_into = self.myStruct.pack_into self.sysmis_ = self.sysmis self.ioUtf8_ = ioUtf8 self.pad_8_lookup = self._getPaddingLookupTable(self.varTypes) self.pad_string = self._pyWriterow_pad_string(isPy3k) self.bytify = bytify(self.fileEncoding) # from py3k module self.encoding = self.fileEncoding ``` -------------------------------- ### Example Multiple Response Set Definitions Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Illustrates the structure of different types of multiple response sets (categorical, dichotomous, extended dichotomous) used within the savReaderWriter library. ```python categorical = {b"setType": b"C", b"label": b"labelC", b"varNames": [b"salary", b"educ"]} dichotomous1 = {b"setType": b"D", b"label": b"labelD", b"varNames": [b"salary", b"educ"], b"countedValue": b"Yes"} dichotomous2 = {b"setType": b"D", b"label": b"", b"varNames": [b"salary", b"educ", b"jobcat"], b"countedValue": b"No"} extended1 = {b"setType": b"E", b"label": b"", b"varNames": [b"mevar1", b"mevar2", b"mevar3"], b"countedValue": b"1", b"firstVarIsLabel": True} extended2 = {b"setType": b"E", b"label": b"Enhanced set with user specified label", b"varNames": [b"mevar4", b"mevar5", b"mevar6"], b"countedValue": b"Yes", b"firstVarIsLabel": False} multRespDefs = {b"testSetC": categorical, b"testSetD1": dichotomous1, b"testSetD2": dichotomous2, b"testSetEx1": extended1, b"testSetEx2": extended2} ``` -------------------------------- ### Get Hash Value Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savReader.html Returns a hash value for the SavReader object, ensuring it is hashable and can be used in sets or as dictionary keys. ```python def __hash__(self): """This function returns a hash value for the object to ensure it is hashable.""" return id(self) ``` -------------------------------- ### Get Number of Cases Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savReader.html Returns the total number of cases (rows) in the SPSS data file. Can be used with the len() function. ```python def __len__(self): """ This function reports the number of cases (rows) in the spss data file. For example: len(SavReader(savFileName))""" return self.nCases ``` -------------------------------- ### SavReader.all() Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/savReader.html Returns all records from the SAV file as a list of lists. ```APIDOC ## SavReader.all() ### Description This convenience function returns all the records. ### Request Example ```python data = SavReader("someFile.sav") list_of_lists = data.all() data.close() ``` ``` -------------------------------- ### Get Variable Roles Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Retrieves variable role information from an SPSS file. Returns a dictionary mapping variable names to their roles. ```python @property @decode def varRoles(self): """Get/Set `VARIABLE ROLES`. Returns/Takes a dictionary of the form `{varName: varRole}`, where varRoles may be any of the following: 'both', 'frequency', 'input', 'none', 'partition', 'record ID', 'split', 'target'""" func = self.spssio.spssGetVarRole func.argtypes = [c_int, c_char_p, POINTER(c_int)] roles = {0: b"input", 1: b"target", 2: b"both", 3: b"none", 4: b"partition", 5: b"split", 6: b"frequency", 7: b"record ID"} varRoles = {} varRole_ = c_int() for varName in self.varNames: vName = self.vNames[varName] retcode = func(self.fh, c_char_py3k(vName), varRole_) varRole = roles.get(varRole_.value) varRoles[varName] = varRole if retcode: msg = "Problem getting variable role for variable %r" checkErrsWarns(msg, retcode) return varRoles ``` -------------------------------- ### Column Widths Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Enables getting and setting the display width for variables. A width of zero indicates that SPSS should determine an appropriate width. ```APIDOC ## Column Widths ### Description Get or set the display width for variables. Returns a dictionary of `{varName: }`. A value of zero means SPSS will set an appropriate width. ### Method `columnWidths` (property) ### Parameters #### Request Body (for setter) - **varColumnWidths** (dict) - Required - A dictionary where keys are variable names (string) and values are the desired column widths (integer). A value of 0 lets SPSS determine the width. ### Request Example ```python # Get column widths widths = sav_writer.columnWidths # Set column widths sav_writer.columnWidths = {'Age': 10, 'Name': 25, 'Salary': 0} ``` ### Response #### Success Response (200) - **columnWidths** (dict) - A dictionary mapping variable names to their integer column widths. ``` -------------------------------- ### Context Manager Methods Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Methods for using SavWriter within a 'with' statement for automatic file handling. ```APIDOC ## SavWriter Context Manager ### `__enter__` This function returns the writer object itself so the writerow and writerows methods become available for use with ‘with’ statements. ### `__exit__` This function closes the spss data file. Warning: Always ensure the the .sav file is properly closed, either by using a context manager (`with` statement) or by using `close()`. ``` -------------------------------- ### Variable Labels Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Get or set the variable labels for the SAV file. This is a dictionary where keys are variable names and values are their corresponding labels. ```APIDOC ## Property: varLabels ### Description Get or set the variable labels for the SAV file. This is a dictionary where keys are variable names and values are their corresponding labels. ### Example ```python # Getting variable labels variable_labels = reader.varLabels # Setting variable labels reader.varLabels = {b'salary': b'Salary (dollars)', b'educ': b'Educational level (years)'} ``` ### Get Returns a dictionary of the form `{varName: varLabel}`. ### Set Takes a dictionary of the form `{varName: varLabel}`. ``` -------------------------------- ### SavReader.getHeader Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Returns a list of variable names from the SAV file, optionally filtered by a selection. ```APIDOC ## getHeader ### Description This function returns the variable names, or a selection thereof (as specified as a list using the `selectVars` parameter), as a list. ### Parameters * **selectVars** (list): An optional list of variable names to select. ### Example ```python data = SavReader(savFileName) variable_names = data.getHeader() print(variable_names) selected_vars = data.getHeader(['var1', 'var2']) print(selected_vars) data.close() ``` ``` -------------------------------- ### Get Value Labels (Numeric) Source: https://pythonhosted.org/savReaderWriter/_modules/savReaderWriter/header.html Retrieves value labels for numeric variables. It first determines the array size and then fetches the labels. ```python # step 1a: get array size (numeric values) if self.varTypes[varName] == 0: valuesArr, labelsArr = initArrays(True) func = funcN func.argtypes = [c_int, c_char_p, POINTER(POINTER(c_double * 0)), POINTER(POINTER(c_char_p * 0)), POINTER(c_int)] retcode = func(self.fh, c_char_py3k(vName), valuesArr, labelsArr, numLabels) valuesArr, labelsArr = initArrays(True, numLabels.value) func.argtypes = [c_int, c_char_p, POINTER(POINTER(c_double * numLabels.value)), POINTER(POINTER(c_char_p * numLabels.value)), POINTER(c_int)] ``` -------------------------------- ### multRespDefs Source: https://pythonhosted.org/savReaderWriter/generated_api_documentation.html Get or set MRSETS (multiple response) sets. This method returns or accepts a dictionary defining multiple response sets. ```APIDOC ## multRespDefs ### Description Get/Set MRSETS (multiple response) sets. Returns/takes a dictionary of the form: * multiple category sets: {setName: {“setType”: “C”, “label”: lbl, “varNames”: []}} * multiple dichotomy sets: {setName: {“setType”: “D”, “label”: lbl, “varNames”: [], “countedValue”: countedValue}} * extended multiple dichotomy sets: {setName: {“setType”: “E”, “label”: lbl, “varNames”: [], “countedValue”: countedValue, ‘firstVarIsLabel’: }} Note. You can get values of extended multiple dichotomy sets with getMultRespSetsDefEx, but you cannot write extended multiple dichotomy sets. ```