save_data

pyhelpers.store.save_data(data, path_to_file, err_warning=True, confirmation_required=True, raise_error=False, **kwargs)[source]

Saves data to a file in a specific format.

Parameters:
  • data (Any) –

    The data to be saved, which can be:

  • path_to_file (str | os.PathLike) – The path of the file where the data will be stored.

  • err_warning (bool) – Whether to display a warning message if an unknown error occurs; defaults to True.

  • confirmation_required (bool) – Whether user confirmation is required to proceed; defaults to True.

  • raise_error (bool) – Whether to raise the provided exception; if raise_error=False (default), the error will be suppressed.

  • kwargs – [Optional] Additional parameters for one of the following functions: save_pickle(), save_spreadsheet(), save_spreadsheets(), save_json(), save_joblib(), save_feather(), save_figure() or save_web_page_as_pdf().

Examples:

>>> from pyhelpers.store import save_data
>>> from pyhelpers.dirs import cd
>>> from pyhelpers._cache import example_dataframe
>>> data_dir = cd("tests", "data")
>>> # Get an example dataframe
>>> dat = example_dataframe()
>>> dat
            Longitude   Latitude
City
London      -0.127647  51.507322
Birmingham  -1.902691  52.479699
Manchester  -2.245115  53.479489
Leeds       -1.543794  53.797418
>>> # Save the data to files different formats:
>>> dat_pathname = cd(data_dir, "dat.pickle")
>>> save_data(dat, dat_pathname, verbose=True)
Saving "dat.pickle" to ".\tests\data\" ... Done.
>>> dat_pathname = cd(data_dir, "dat.csv")
>>> save_data(dat, dat_pathname, index=True, verbose=True)
Saving "dat.csv" to ".\tests\data\" ... Done.
>>> dat_pathname = cd(data_dir, "dat.xlsx")
>>> save_data(dat, dat_pathname, index=True, verbose=True)
Saving "dat.xlsx" to ".\tests\data\" ... Done.
>>> dat_pathname = cd(data_dir, "dat.txt")
>>> save_data(dat, dat_pathname, index=True, verbose=True)
Saving "dat.txt" to ".\tests\data\" ... Done.
>>> dat_pathname = cd(data_dir, "dat.feather")
>>> save_data(dat, dat_pathname, index=True, verbose=True)
Saving "dat.feather" to ".\tests\data\" ... Done.
>>> # Convert `dat` to JSON format
>>> import json
>>> dat_ = json.loads(dat.to_json(orient='index'))
>>> dat_
{'London': {'Longitude': -0.1276474, 'Latitude': 51.5073219},
 'Birmingham': {'Longitude': -1.9026911, 'Latitude': 52.4796992},
 'Manchester': {'Longitude': -2.2451148, 'Latitude': 53.4794892},
 'Leeds': {'Longitude': -1.5437941, 'Latitude': 53.7974185}}
>>> dat_pathname = cd(data_dir, "dat.json")
>>> save_data(dat_, dat_pathname, indent=4, verbose=True)
Saving "dat.json" to ".\tests\data\" ... Done.

See also