if __name__ == '__main__':
    DSN = (
        """host=YOUR_DATABASE_HOST port=YOUR_DATABASE_PORT dbname=YOUR_DATABASE_NAME user=YOUR_DATABASE_USER"""
        )
column_names = []
data_rows = []
with psycopg2.connect(DSN) as connection:
    with connection.cursor() as cursor:
        cursor.execute('select field1, field2, fieldn from table1')
column_names = [desc[0] for desc in cursor.description]
for row in cursor:
    data_rows.append(row)
print('Column names: {}\n'.format(column_names))
How do I get a list of column names from a psycopg2 cursor?