'Any way to get the same output as Pandas dataframe in txt file using python?
I am using below python code to get my data frame into txt file. Since I have 9+ column in dataframe, my txt file looks like below. I was wondering if I can get the same output that I have in pandas dataframe to txt file ? Meaning can I get the same output that I am getting if I use print(df) to txt file ?
Python Code:
filename = 'output.txt'
def main():
conn = snowflake.connector.connect()
with open(filename,'w') as my_file:
cur = conn.cursor()
try:
cur.execute(f"""SELECT TABLE_SCHEMA,TABLE_TYPE,TABLE_NAME, ROW_COUNT, DATE(CREATED) AS "TABLE_CREATED_DATE", DATE(LAST_ALTERED) AS "LAST_ALTERED_DATE" FROM TABLES WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_SCHEMA='TPCDS_SF100TCL' AND TABLE_NAME IN ({','.join("'" + x + "'" for x in tables)})
UNION
SELECT TABLE_SCHEMA,TABLE_TYPE,TABLE_NAME, ROW_COUNT, DATE(CREATED) AS "TABLE_CREATED_DATE", DATE(LAST_ALTERED) AS "LAST_ALTERED_DATE" FROM TABLES WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_SCHEMA='TPCDS_SF10TCL'
AND TABLE_NAME IN ({','.join("'" + x + "'" for x in tables)})""")
df = cur.fetch_pandas_all()
df=df.set_index(['TABLE_SCHEMA', 'TABLE_NAME'], drop=True).T
my_file.write(f" {df}")
TXT file output
TABLE_SCHEMA TPCDS_SF100TCL \
TABLE_NAME CALL_CENTER CATALOG_PAGE CUSTOMER CUSTOMER_ADDRESS
TABLE_TYPE BASE TABLE BASE TABLE BASE TABLE BASE TABLE
ROW_COUNT 60 50000 100000000 50000000
TABLE_CREATED_DATE 2022-03-02 2022-03-02 2022-03-02 2022-03-02
LAST_ALTERED_DATE 2022-05-06 2022-03-02 2022-03-02 2022-03-02
TABLE_SCHEMA TPCDS_SF10TCL \
TABLE_NAME CUSTOMER_DEMOGRAPHICS CALL_CENTER CATALOG_PAGE
TABLE_TYPE BASE TABLE BASE TABLE BASE TABLE
ROW_COUNT 1920800 54 40000
TABLE_CREATED_DATE 2022-03-02 2022-03-02 2022-03-02
LAST_ALTERED_DATE 2022-03-02 2022-03-02 2022-03-02
TABLE_SCHEMA
TABLE_NAME CUSTOMER CUSTOMER_DEMOGRAPHICS CUSTOMER_ADDRESS
TABLE_TYPE BASE TABLE BASE TABLE BASE TABLE
ROW_COUNT 65000000 1920800 32500000
TABLE_CREATED_DATE 2022-03-02 2022-03-02 2022-03-02
LAST_ALTERED_DATE 2022-03-02 2022-03-02 2022-03-02
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
