I am trying to use SQLAlchemy to establish a connection to a PostgreSQL Database, execute a SQL query and print the output of the file to a file in linux.
from sqlalchemy import create_engine
import yaml
import csv
outfile = open('/path/filename.csv', 'wb')
outcsv = csv.writer(outfile, delimiter='\t')
with open('config.yml') as f:
cfg = yaml.safe_load(f)
username = cfg['credentials']['username']
password = cfg['credentials']['password']
host = cfg['credentials']['host']
port = cfg['credentials']['port']
dbname = cfg['credentials']['dbname']
engine = create_engine('postgresql://{}:{}@{}:{}/{}'.format(username, password, host, port, dbname))
result = engine.execute("""select * from db.tablename """)
# dump column titles (optional)
outcsv.writerow(x[0] for x in result.description)
# dump rows
outcsv.writerows(result.fetchall())
outfile.close()
However, I am getting the following error message - Traceback (most recent call last): File "", line 12, in AttributeError: 'ResultProxy' object has no attribute 'description'
If I comment the below command, I am successfully able to get the query result but without the headers. outcsv.writerow(x[0] for x in result.description)
Upon researching, I found the method - result._metadata.keys can generate the headers. However, it generates in some form of a list that I can't attach as header.
Please advise if there is any way to get the file header as well as the data into a csv file. Please consider the fact that I am beginner in Python while answering the above.