Tag: drafts

This script compares two CSV files with the same structure and provides list of differences – entries that have been removed or added and per column changes for each entry.

One of the possible scenarios – you have two copies of some data extract in different points of time and want to have an audit log of all the changes. Some people may say “why don’t just use MS Excel vlookups” and even though I do agree that MS Excel is a great tool and vlookups might be convenient for comparing one-two columns, but imagine if your data set contains a lot of columns or/and if you want to set up an automated regular monitoring and keep a log of changes – this is what this script was designed for.

With some minor amendments the same approach can be used for monitoring changes in database tables or any other tabular data structures.

Usage:

Sample data:

1

2

3

4

5

6

7

8

9

10

11

12

# import function:

fromtable_diff importdiff

# set path to 'left' and 'right' files:

file_left="sample/data_export_last_month.csv"

file_right="sample/data_export_this_month.csv"

# define unique identifier:

key_fields=["item","store location"]

# call function:

diff(file_left,file_right,key_fields)

1

2

3

# function returns number of records missing, new and updated:

(1,1,2)

# and if any of these counts is different from zero - creates a diff.csv file:

Optional Parameters:

sqlite_path – path to SQLite file to be created (otherwise – SQLite runs in memory).fields_to_check – list of columns to check (and report about, by default – every column is checked).fields_to_ignore – similar to above, in case it is easier to provide a list of columns to be ignored.keep_tables – working tables in SQLite will be preserved if “yes”diff_csv – name/path for the report file (“diff.csv” by default)

Since SQLite can’t do INSTR (Oracle/MySQL), SUBSTRING_INDEX (MySQL) or CHARINDEX (SQL Server), this is an attempt to do it with help of Python.
It’s one of my very first experiments with Python (although I’m falling in love already :) ) so will need to revisit the actual code, marking it as drafts meanwhile.