def METHOD_NAME(df, filename):
    filename = str(filename)
    if filename.endswith(".csv") or filename.endswith(".csv.gz"):
        df.to_csv(filename, index=False)
    elif filename.endswith(".feather"):
        # zstd is a better option that the default lz4 compression
        df.to_feather(filename, compression="zstd")
    elif filename.endswith(".dta") or filename.endswith(".dta.gz"):
        # Make a shallow copy of the dataframe so we can replace certain
        # columns without duplicating the entire thing in memory
        df = df.copy(deep=False)
        # Replace categorical columns with arrays of strings as Stata's
        # categorical support isn't that great. See:
        # https://github.com/opensafely-core/cohort-extractor/issues/534
        for column, dtype in list(df.dtypes.items()):
            if dtype.name == "category":
                df[column] = df[column].__array__()
        # Encode dates as proper Stata dates (we use "td" as we only need day
        # resolution)
        convert_dates = {
            column: "td"
            for (column, dtype) in df.dtypes.items()
            if dtype.name == "datetime64[ns]"
        }
        # to_stata will infer gzip compression if the filename ends in .gz
        # version 118 is the current recommended version for the version of stata opensafely uses.
        df.to_stata(
            filename, version=118, write_index=False, convert_dates=convert_dates
        )
    else:
        raise RuntimeError(f"Unsupported file format: {filename}")