Skip to content

Instantly share code, notes, and snippets.

@vepetkov
Created December 20, 2019 12:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vepetkov/a24b501e180cc5842b786ae680035239 to your computer and use it in GitHub Desktop.
Save vepetkov/a24b501e180cc5842b786ae680035239 to your computer and use it in GitHub Desktop.
Snowflake Upload Local Files from Python
import os
import snowflake.connector
ctx = snowflake.connector.connect(
authenticator="snowflake",
user=os.getenv("SNOWSQL_USER"),
password=os.getenv("SNOWSQL_PWD"),
account=os.getenv("SNOWSQL_ACCOUNT"),
warehouse=os.getenv("SNOWSQL_WAREHOUSE")
)
cs = ctx.cursor()
# Params
schemaName = "DEV.DEMO"
tblName = "UPLOAD_TEST"
filePath = "./data/Users_20191224.csv"
# Create the temp table
createStmt = f"""CREATE OR REPLACE TRANSIENT TABLE {schemaName}.{tblName} (
title_name string,
period_start_date_id string,
period_end_date_id string,
country_name string,
region_name string,
platform_name string,
total_unique_users string,
new_unique_users string
);"""
cs.execute(createStmt)
# Upload the local file to the internal table stage
uploadStmt = f'put file://{filePath} @%{tblName};'
cs.execute(f"use schema {schemaName};") # or set the Db & Scheme for the whole connection directly
cs.execute(uploadStmt)
# Check the uploads
cs.execute(f"list @%{tblName};")
uploadedFiles = cs.fetchall()
uploadedFiles
# Import the data from the CSV to the table
importStmt = f"""COPY INTO {schemaName}.{tblName}
PATTERN = '.*.gz'
FORCE=TRUE
ON_ERROR = CONTINUE
FILE_FORMAT = (TYPE = CSV SKIP_HEADER=1);"""
cs.execute(importStmt)
rsult = cs.fetchall()
rsult
# Check the imported data
cs.execute(f"select * from {schemaName}.{tblName} limit 10;")
rsult = cs.fetchall()
rsult
cs.close()
ctx.close()
@Manocs11
Copy link

sir, why you gave "f"in execute statements. Any reason

cs.execute(f"select * from {schemaName}.{tblName} limit 10;")

@vepetkov
Copy link
Author

This is just an f-String available in Python 3 - it allows you to format it easily and insert variables into the string. The one above just inserts the values of “schemaName” and “tblName” into the string instead of hard-coding them.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment