File size: 4,974 Bytes
d3d0f34 3aca217 d3d0f34 3aca217 d3d0f34 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | import subprocess
from pathlib import Path
import pandas as pd
CSV_DIR = None
while CSV_DIR is None:
user_input = input("Enter the full path to the CSV directory: ").strip()
if not user_input:
continue
csv_path = Path(user_input)
if not csv_path.is_dir():
print(f"Directory not found: {csv_path}. Please try again.")
CSV_DIR = None
continue
CSV_DIR = csv_path
OUTPUT_FILE = Path("./schema_comparison.txt")
N_ROWS = 1000
SAMPLE_ROWS = 5
output_lines = []
def output(*args, **kwargs):
line = " ".join(str(a) for a in args)
print(line, **kwargs)
output_lines.append(line)
def get_row_count(filepath: Path) -> int:
result = subprocess.run(
["wc", "-l", str(filepath)],
capture_output=True,
text=True,
)
return int(result.stdout.strip().split()[0]) - 1
def load_schema(filepath: Path, nrows: int = N_ROWS) -> tuple[dict, pd.DataFrame]:
try:
df = pd.read_csv(filepath, nrows=nrows)
except Exception as e:
output(f"Warning: Could not read {filepath.name}: {e}")
return {}, pd.DataFrame()
schema = dict(df.dtypes)
return schema, df
def compare_schemas(schema1: dict, schema2: dict):
cols1 = set(schema1.keys())
cols2 = set(schema2.keys())
missing_in_1 = cols2 - cols1
missing_in_2 = cols1 - cols2
common_cols = cols1 & cols2
dtype_mismatches = {}
for col in common_cols:
if str(schema1[col]) != str(schema2[col]):
dtype_mismatches[col] = (schema1[col], schema2[col])
if missing_in_1 or missing_in_2 or dtype_mismatches:
return False, missing_in_1, missing_in_2, dtype_mismatches
return True, None, None, None
def print_mismatch(
ref_name: str,
target_name: str,
missing_in_ref: set,
missing_in_target: set,
dtype_mismatches: dict,
ref_df: pd.DataFrame,
target_df: pd.DataFrame,
):
output(f"\n{'=' * 60}")
output(f"SCHEMA MISMATCH: {target_name} vs. Reference ({ref_name})")
output(f"{'=' * 60}")
if missing_in_ref:
output(
f"\nColumns in {target_name} but missing in ({ref_name}): {missing_in_ref}"
)
if missing_in_target:
output(
f"\nColumns in reference ({ref_name}) but missing in {target_name}: {missing_in_target}"
)
if dtype_mismatches:
output("\n--- DTYPE MISMATCHES ---")
for col, (dt_ref, dt_target) in dtype_mismatches.items():
output(f" {col}: Reference={dt_ref}, {target_name}={dt_target}")
output("\n--- SAMPLE DATA FOR MISMATCHED COLUMNS ---")
for col in dtype_mismatches.keys():
output(f"\n--- {col} ---")
output(f"Reference ({ref_name}) ({SAMPLE_ROWS} rows):")
output(ref_df[col].head(SAMPLE_ROWS).to_list())
output(f"{target_name} [{SAMPLE_ROWS} rows]:")
output(target_df[col].head(SAMPLE_ROWS).to_list())
def main():
global output_lines
csv_files = sorted(list(CSV_DIR.glob("*.csv")))
if not csv_files:
output(f"No CSV files found in {CSV_DIR}")
output(f"\n{'#' * 60}")
output(f"ANALYZING {len(csv_files)} CSV FILES IN: {CSV_DIR.resolve()}")
output(f"{'#' * 60}")
file_stats = {}
schemas = {}
dataframes = {}
for f in csv_files:
row_count = get_row_count(f)
schema, df = load_schema(f)
schemas[f.name] = schema
dataframes[f.name] = df
file_stats[f.name] = {
"row_count": row_count,
"col_count": len(df.columns),
}
ref_file = csv_files[0]
ref_name = ref_file.name
output(f"\nUsing '{ref_name}' as the reference schema baseline.\n")
has_mismatch = False
for f in csv_files[1:]:
target_name = f.name
is_match, missing_in_ref, missing_in_target, dtype_mismatches = compare_schemas(
schemas[ref_name], schemas[target_name]
)
if not is_match:
has_mismatch = True
print_mismatch(
ref_name,
target_name,
missing_in_ref,
missing_in_target,
dtype_mismatches,
dataframes[ref_name],
dataframes[target_name],
)
if not has_mismatch:
output("SUCCESS: All CSV files share a 100% identical schema!")
output(f"\n{'#' * 60}")
output("FILE STATISTICS SUMMARY")
output(f"{'#' * 60}")
output(f"\n{'File':<65} {'Rows':>12} {'Columns':>10}")
output("-" * 89)
grand_total_rows = 0
for name, stats in sorted(file_stats.items()):
output(f"{name:<65} {stats['row_count']:>12,} {stats['col_count']:>10}")
grand_total_rows += stats["row_count"]
output("-" * 89)
output(f"{'TOTAL':<65} {grand_total_rows:>12,}")
OUTPUT_FILE.write_text("\n".join(output_lines))
print(f"\nOutput saved to {OUTPUT_FILE}")
if __name__ == "__main__":
main()
|