[英]Python Output Snowflake Connector To CSV
I currently am trying to print the output of a snowflake connector query and write it to csv, but I'm having issues doing this.我目前正在尝试打印雪花连接器查询的 output 并将其写入 csv,但我在执行此操作时遇到问题。 Currently, my code example looks like:
目前,我的代码示例如下所示:
query = '''SELECT TOP 10 * FROM TABLE;'''
conn = snowflake.connector.connect(user='XXXX',
password='XXXX',
account='XXXX')
query_output = conn.cursor().execute(query)
Is there a way for me to print the output of the query, like maybe print(query_output)
and then also write it to csv like query_output.to_csv(path)
?有没有办法让我打印查询的 output ,例如
print(query_output)
然后也将其写入 csv ,例如query_output.to_csv(path)
?
I highly recommend using Pandas ' DataFrames API.我强烈推荐使用Pandas的 DataFrames API。 Amongst several other data transformation and analysis capabilities, it has an excellent CSV reader and writer implementation that is very flexible .
在其他几种数据转换和分析功能中,它具有出色的 CSV 读写器实现, 非常灵活。
Snowflake's Python Connector also natively supports transforming results as Pandas DataFrame objects. Snowflake 的 Python 连接器本身也支持将结果转换为 Pandas DataFrame 对象。
A very simple, adapted example is provided below (1 added line):下面提供了一个非常简单的改编示例(添加了 1 行):
query = '''SELECT TOP 10 * FROM TABLE;'''
conn = snowflake.connector.connect(user='XXXX',
password='XXXX',
account='XXXX')
query_output = conn.cursor().execute(query)
## You may have to run: pip3 install --user pandas ##
query_output.fetch_pandas_all().to_csv("/path/to/write/table.csv")
The default CSV formatting uses ,
as the separator, OS-specific newlines ( \n
except on Windows, which uses \r\n
), and minimal quoting (auto-quotes VARCHAR
columns that carry delimiter characters within them).默认的 CSV 格式使用
,
作为分隔符,操作系统特定的换行符( \n
除了在 Windows 上,它使用\r\n
)和最少的引用(自动引用VARCHAR
列,其中包含分隔符)。
You can do like below :
---------------------------------------------------------------
import csv
.....
.....
.....
rows=cur.fetchall()
column_names = [i[0] for i in cur.description]
fp = open('samplefile.csv', 'w')
myFile = csv.writer(fp, lineterminator = '\n')
myFile.writerow(column_names)
myFile.writerows(rows)
fp.close()
.....
.....
You can use this to print the results.您可以使用它来打印结果。 To save it in csv, just save the results in a dataframe using for loop and then use df.to_csv
要将其保存在 csv 中,只需使用 for 循环将结果保存在 dataframe 中,然后使用 df.to_csv
cursor.execute(query)
sql_result = cursor.fetchall()
print(sql_result) ## just print the results or use the for loop below to print the results row by row
for row in sql_result:
print(row)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.