Serialize a Pandas dataframe to a geojson format Python dictionary / file

def df_to_geojson(df, properties=None, lat='lat', lon='lon', precision=6, date_format='epoch', filename=None):
    """Serialize a Pandas dataframe to a geojson format Python dictionary / file
    """

    if not properties:
        # if no properties are selected, use all properties in dataframe
        properties = [c for c in df.columns if c not in [lon, lat]]

    for prop in properties:
        # Check if list of properties exists in dataframe columns
        if prop not in list(df.columns):
            raise ValueError(
                'properties must be a valid list of column names from dataframe')
        if prop in [lon, lat]:
            raise ValueError(
                'properties cannot be the geometry longitude or latitude column')

    # convert dates/datetimes to preferred string format if specified
    df = convert_date_columns(df, date_format)

    if filename:
        with open(filename, 'w') as f:
            # Overwrite file if it already exists
            pass

        with open(filename, 'a+') as f:

            # Write out file to line
            f.write('{"type": "FeatureCollection", "features": [\n')
            # Iterate over enumerated iterrows as index from iterrows alone could be non-sequential
            for i, (index, row) in enumerate(df[[lon, lat] + properties].iterrows()):
                if i == 0:
                    f.write(geojson.dumps(row_to_geojson(row, lon, lat, precision, date_format)) + '\n')
                else:
                    f.write(',' + geojson.dumps(row_to_geojson(row, lon, lat, precision, date_format)) + '\n')
            f.write(']}')

            return {
                "type": "file",
                "filename": filename,
                "feature_count": df.shape[0]
            }
    else:
        features = []
        df[[lon, lat] + properties].apply(lambda x: features.append(
            row_to_geojson(x, lon, lat, precision, date_format)), axis=1)
        return geojson.FeatureCollection(features)