Python Datacompy library: how to save report string into a csv file?

Viewed 1883

I'm comparing between two data frames using Datacompy, but how can I save the final result as an excel sheet or csv file? I got a string as an output, but how can I save it as a CSV.

import pandas as pd
df1_1=pd.read_csv('G1-1.csv')
df1_2=pd.read_csv('G1-2.csv')

import datacompy
compare = datacompy.Compare(
    df1_1,
    df1_2,
    join_columns='SAMPLED CONTENT (URL to content)', 
)

print(compare.report())
3 Answers

I have tried this, and it worked for me:

with open('//Path', encoding='utf-8') as report_file:
    report_file.write(compare.report())

If you just using pandas, you can try pandas's own way to write into csv:

> df = pd.DataFrame([['yy','rr'],['tt', 'rr'],['cc', 'rr']], index=range(3),
                  columns=['a', 'b'])

> df.to_csv('compare.csv')

I hadn't used datacompy, but I suggest that you can make your results into a dataframe, then you can use the to_csv way.

This is working fine me also Full code

 compare = datacompy.Compare(
    Oracle_DF1,PostgreSQL_DF2, 
    join_columns=['c_transaction_cd','c_anti_social_force_req_id'],  #You can also specify a list of columns
    abs_tol=0, 
    rel_tol=0,
    df1_name = 'Oracle Source', 
    df2_name = 'PostgrSQL Reference'   
    )
    compare.matches(ignore_extra_columns=False)
    Report = compare.report()    csvFileToWrite=r'D://Postgres_Problem_15Feb21//Oracle_PostgreSQLDataFiles//Sample//summary.csv'
    with open(csvFileToWrite,mode='r+',encoding='utf-8') as report_file:
        report_file.write(compare.report())
Related