[Python] Write Spss with Python with value labels and Data labels

Discussão em 'Python' iniciado por Stack, Março 26, 2025.

  1. Stack

    Stack Membro Participativo

    i have tried this code but it results in vanishing spss value and data labels.

    pyreadstat.write_sav(df)

    If there is another way to write spss file without lossing value labels and data labels. Kindly let me know.

    Also tried below mentioned code But unable to access file location. In my case i have to do work on spss file in python and write it back in spss for the users. Can anyone guide how to write spss file in python without losing labels and value labels please?

    Code:

    from pyreadstat import write_sav

    class TempFile(type(pathlib.Path())): # type: ignore
    def __exit__(self, exc_type, exc_val, exc_tb):
    filepath = str(self.absolute())
    try:
    os.remove(filepath)
    except OSError:
    logger.exception('romve temporary file: %s failed!', filepath)
    self._closed = True

    class SpssTool:
    @classmethod
    def to_spss(cls, df: DataFrame, io: BytesIO, metadata: metadata_container, *, compress: bool = False):
    """Writes a pandas dataframe to a BytesIO object.

    Parameters
    ----------
    df : pandas.DataFrame
    pandas data frame to write to sav or zsav
    io : BytesIO
    the buffer to save spss file
    metadata: metadata_container
    spss file meta data container
    compress : bool
    whether compress to zsav.
    """

    df.columns = SpssTool.get_legal_column_names(df.columns.to_list())

    with TempFile(f'/tmp/{uuid4().hex}.{"zsav" if compress else "sav"}') as fp:
    write_sav(
    df=df,
    dst_path=fp,
    column_labels=metadata.column_labels if metadata else None,
    variable_value_labels=dict(metadata.variable_value_labels) if metadata else {},
    variable_measure=metadata.variable_measure if metadata else None,
    )
    io.write(fp.read_bytes())

    Continue reading...

Compartilhe esta Página