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()