'Write query results to file.
Acceptable formats are:
- csv:
comma-seperated-values file.  This is the default format.
- json:
JSON array.  Each element in the array is a different row.
- ndjson:
JSON array but each element is new-line deliminated
instead of comman deliminated like in `json`
This requires a significant amount of cleanup.
Pandas doesn\'t handle output to CSV and json in a uniform way.
This is especially painful for datetime types.
Pandas wants to write them as strings in CSV,
but as milisecond Unix timestamps.
By default, this function will try and leave all values as
they are represented in Salesforce.
You use the `coerce_to_timestamp` flag to force all datetimes
to become Unix timestamps (UTC).
This is can be greatly beneficial as it will make all of your
datetime fields look the same,
and makes it easier to work with in other database environments
:param query_results:       the results from a SQL query
:param filename:            the name of the file where the data
should be dumped to
:param fmt:                 the format you want the output in.
*Default:* csv.
:param coerce_to_timestamp: True if you want all datetime fields to be
converted into Unix timestamps.
False if you want them to be left in the
same format as they were in Salesforce.
Leaving the value as False will result
in datetimes being strings.
*Defaults to False*
:param record_time_added:   *(optional)* True if you want to add a
Unix timestamp field to the resulting data
that marks when the data
was fetched from Salesforce.
*Default: False*.'

def write_object_to_file(self, query_results, filename, fmt='csv', coerce_to_timestamp=False, record_time_added=False):

    fmt = fmt.lower()
    if (fmt not in ['csv', 'json', 'ndjson']):
        raise ValueError('Format    value    is    not    recognized:    {0}'.format(fmt))
    df = pd.DataFrame.from_records(query_results, exclude=['attributes'])
    df.columns = [c.lower() for c in df.columns]
    if (coerce_to_timestamp and (df.shape[0] > 0)):
        object_name = query_results[0]['attributes']['type']
        logging.info('Coercing    timestamps    for:    {0}'.format(object_name))
        schema = self.describe_object(object_name)
        possible_timestamp_cols = [i['name'].lower() for i in schema['fields'] if ((i['type'] in ['date', 'datetime']) and (i['name'].lower() in df.columns))]
        df[possible_timestamp_cols] = df[possible_timestamp_cols].apply((lambda x: self._to_timestamp(x)))
    if record_time_added:
        fetched_time = time.time()
        df['time_fetched_from_salesforce'] = fetched_time
    if (fmt == 'csv'):
        logging.info('Cleaning    data    and    writing    to    CSV')
        possible_strings = df.columns[(df.dtypes == 'object')]
        df[possible_strings] = df[possible_strings].apply((lambda x: x.str.replace('\r\n', '')))
        df[possible_strings] = df[possible_strings].apply((lambda x: x.str.replace('\n', '')))
        df.to_csv(filename, index=False)
    elif (fmt == 'json'):
        df.to_json(filename, 'records', date_unit='s')
    elif (fmt == 'ndjson'):
        df.to_json(filename, 'records', lines=True, date_unit='s')
    return df
