aboutsummaryrefslogtreecommitdiffstats
path: root/fg21sim/utils/io.py
blob: 4d9999eddd0747ce35861e29bec0467a3c22659b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Copyright (c) 2017 Weitian LI <weitian@aaronly.me>
# MIT license

"""
Input/output utilities.
"""

import os
import logging

import pandas as pd


logger = logging.getLogger(__name__)


def dataframe_to_csv(df, outfile, clobber=False):
    """
    Save the given Pandas DataFrame into a CSV text file.

    Parameters
    ----------
    df : `~pandas.DataFrame`
        The DataFrame to be saved to the CSV text file.
    outfile : string
        The path to the output CSV file.
    clobber : bool, optional
        Whether overwrite the existing output file?
        Default: False
    """
    if not isinstance(df, pd.DataFrame):
        raise TypeError("Not a Pandas DataFrame!")

    # Create directory if necessary
    dirname = os.path.dirname(outfile)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
        logger.info("Created output directory: {0}".format(dirname))

    if os.path.exists(outfile):
        if clobber:
            logger.warning("Remove existing file: {0}".format(outfile))
            os.remove(outfile)
        else:
            raise OSError("Output file exists: {0}".format(outfile))
    df.to_csv(outfile, header=True, index=False)
    logger.info("Saved DataFrame to CSV file: {0}".format(outfile))