Use cursor.copy_expert(), place your query as an argument to COPY
command, e.g.:
sql = """
copy (
select *
from my_table
where id < 5
order by id
) to stdout
"""
with open('/data/my_file.txt', 'w') as fp:
cursor.copy_expert(sql, fp)
Read also about Postgres COPY command.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…