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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
| import os import sys import re import json import logging import chardet from datetime import datetime
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', stream=sys.stderr) logger = logging.getLogger(__name__)
SAMPLE_SIZE = 10000
RESULT_KEYS = [ "file_name", "old_file_path", "new_file_path", "status", "encoding_diff", "count_diff", "size_diff", "col_count_diff", "decimal_diff", "date_diff", "content_lookup_diff", ]
def detect_encoding(file_path): """检测文件编码""" try: with open(file_path, 'rb') as f: raw_data = f.read(60000) if not raw_data: return 'utf-8' result = chardet.detect(raw_data) encoding = (result or {}).get('encoding') or 'utf-8' if encoding in ['GB2312', 'GBK']: encoding = 'GB18030' return encoding except Exception as e: logger.warning(f"Encoding detection failed for {file_path}: {e}") return 'utf-8'
def read_lines_streaming(file_path, encoding, limit=None): """生成器:逐行读取文件,节省内存(仅去除行尾换行,保留行内内容)""" try: with open(file_path, 'r', encoding=encoding, errors='ignore') as f: count = 0 for line in f: if limit and count >= limit: break yield line.rstrip('\n').rstrip('\r') count += 1 except Exception as e: logger.error(f"Error reading file {file_path}: {e}")
def parse_separator(hex_sep): """将十六进制字符串转换为实际的分隔符字符串(跨系统/跨编码兼容)
支持单字节或多字节分隔符,例如: "7C" -> "|" "09" -> "\\t" "7F5E" -> "\\x7f^" "EFFBC8C" -> 中文全角逗号"," """ if not hex_sep: raise ValueError("分隔符十六进制为空") h = str(hex_sep).strip().lower() if h.startswith('0x'): h = h[2:] try: raw = bytes.fromhex(h) except ValueError: raise ValueError(f"非法的分隔符十六进制: {hex_sep!r}(应为偶数字符,如 7C / 7F5E)") if not raw: raise ValueError("分隔符十六进制解码为空字节") for enc in ('utf-8', 'latin-1'): try: return raw.decode(enc) except UnicodeDecodeError: continue return raw.decode('latin-1')
def is_valid_date_str(val): """严格判断一个字符串是否为合法的日期/时间格式""" if not val or not isinstance(val, str): return False val = val.strip() if len(val) < 8: return False if val.isdigit(): if len(val) == 8: try: datetime.strptime(val, "%Y%m%d") return True except ValueError: return False return False date_patterns = [ (r"\d{4}[-/.]\d{1,2}[-/.]\d{1,2}$", ["%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d"]), (r"\d{4}[-/.]\d{1,2}[-/.]\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2}$", ["%Y-%m-%d %H:%M:%S", "%Y/%m/%d %H:%M:%S"]), ] for pattern, fmts in date_patterns: if re.fullmatch(pattern, val): for fmt in fmts: try: dt_obj = datetime.strptime(val, fmt) if 1900 <= dt_obj.year <= 2100: return True except ValueError: continue return False
def get_standard_format(val): """获取日期的标准格式字符串""" val = val.strip() formats_to_try = [ "%Y-%m-%d", "%Y/%m/%d", "%Y-%m-%d %H:%M:%S", "%Y/%m/%d %H:%M:%S", "%Y%m%d", "%Y-%m-%d %H:%M:%S.%f" ] for fmt in formats_to_try: try: datetime.strptime(val, fmt) return fmt except ValueError: continue return None
def get_number_format_template(val): """ 获取数字的格式模板。 返回: (is_decimal, int_len, dec_len) 例如: "01.20" -> (True, 2, 2), "100" -> (False, 3, 0) """ val = val.strip() if not val: return None is_negative = val.startswith('-') clean_val = val.lstrip('-') if '.' in clean_val: parts = clean_val.split('.') int_part = parts[0] dec_part = parts[1] return (True, len(int_part), len(dec_part)) else: return (False, len(clean_val), 0)
def analyze_columns(lines, sep): """分析列的类型,返回日期列和数值列的索引集合(按文件各自的分隔符)""" col_types = {} for line in lines: if not line.strip(): continue parts = line.split(sep) for i, val in enumerate(parts): val = val.strip() if not val: continue stats = col_types.setdefault(i, {'date': 0, 'numeric': 0, 'total': 0}) stats['total'] += 1 if is_valid_date_str(val): stats['date'] += 1 try: float(val) if '.' in val: stats['numeric'] += 1 except ValueError: pass date_cols = set() numeric_cols = set() for idx, stats in col_types.items(): if stats['total'] > 5 and (stats['date'] / stats['total']) > 0.8: date_cols.add(idx) elif stats['total'] > 5 and (stats['numeric'] / stats['total']) > 0.8: numeric_cols.add(idx) return date_cols, numeric_cols
def count_lines_fast(path): """快速统计文件行数(按字节统计 \\n,兼容 Windows CRLF)""" count = 0 with open(path, 'rb') as f: for chunk in iter(lambda: f.read(8192 * 1024), b''): count += chunk.count(b'\n') return count
def first_non_empty(lines): for ln in lines: if ln.strip(): return ln return None
def _error_result(old_file, new_file, status, err): """统一的错误结果结构,保证 Excel 汇总能读取到所有字段""" return { "file_name": os.path.basename(old_file), "old_file_path": old_file, "new_file_path": new_file, "status": status, "error": str(err), "encoding_diff": "ERROR", "count_diff": "ERROR", "size_diff": "ERROR", "col_count_diff": "ERROR", "decimal_diff": "ERROR", "date_diff": "ERROR", "content_lookup_diff": "ERROR", }
def _empty_result(old_file, new_file): """样本为空时的结果""" return { "file_name": os.path.basename(old_file), "old_file_path": old_file, "new_file_path": new_file, "status": "OK", "encoding_diff": "N/A", "count_diff": "N/A", "size_diff": "N/A", "col_count_diff": "N/A (Empty)", "decimal_diff": "N/A", "date_diff": "N/A", "content_lookup_diff": "N/A (Empty Sample)", }
def compare_files(old_file, new_file, old_hex_sep, new_hex_sep): try: old_sep = parse_separator(old_hex_sep) new_sep = parse_separator(new_hex_sep) except ValueError as e: return _error_result(old_file, new_file, "ERROR", e)
old_size = os.path.getsize(old_file) new_size = os.path.getsize(new_file) old_enc = detect_encoding(old_file) new_enc = detect_encoding(new_file)
old_lines_count = count_lines_fast(old_file) new_lines_count = count_lines_fast(new_file)
results = { "file_name": os.path.basename(old_file), "old_file_path": old_file, "new_file_path": new_file, "status": "OK", "encoding_diff": "OK" if old_enc == new_enc else f"{old_enc} | {new_enc}", "count_diff": "OK" if old_lines_count == new_lines_count else f"{old_lines_count} | {new_lines_count}", "size_diff": "OK" if old_size == new_size else f"{old_size} | {new_size}", "col_count_diff": "OK", "decimal_diff": "OK", "date_diff": "OK", "content_lookup_diff": "OK", }
logger.info(f"Sampling data from {old_file} ...") old_sample = list(read_lines_streaming(old_file, old_enc, SAMPLE_SIZE + 1)) new_sample = list(read_lines_streaming(new_file, new_enc, SAMPLE_SIZE + 1))
if not old_sample or not new_sample: return _empty_result(old_file, new_file)
old_first = first_non_empty(old_sample) new_first = first_non_empty(new_sample) old_col_count = len(old_first.split(old_sep)) if old_first else 0 new_col_count = len(new_first.split(new_sep)) if new_first else 0 results["col_count_diff"] = "OK" if old_col_count == new_col_count else f"{old_col_count} | {new_col_count}"
date_cols_old, numeric_cols_old = analyze_columns(old_sample, old_sep) date_cols_new, numeric_cols_new = analyze_columns(new_sample, new_sep) date_cols = sorted(date_cols_old & date_cols_new) numeric_cols = sorted(numeric_cols_old & numeric_cols_new)
date_diffs = [] decimal_diffs = [] min_rows = min(len(old_sample), len(new_sample)) max_cols = max(old_col_count, new_col_count)
for r_idx in range(min_rows): old_parts = old_sample[r_idx].split(old_sep) new_parts = new_sample[r_idx].split(new_sep) for c_idx in range(max_cols): ov = old_parts[c_idx].strip() if c_idx < len(old_parts) else "" nv = new_parts[c_idx].strip() if c_idx < len(new_parts) else ""
if c_idx in date_cols and ov and nv: of = get_standard_format(ov) nf = get_standard_format(nv) if of and nf and of != nf and len(date_diffs) < 20: date_diffs.append(f"Row{r_idx + 1}|Col{c_idx + 1}: Old[{ov}]({of}) vs New[{nv}]({nf})")
if c_idx in numeric_cols and ov and nv: ot = get_number_format_template(ov) nt = get_number_format_template(nv) if ot and nt and ot != nt and len(decimal_diffs) < 20: decimal_diffs.append( f"Row{r_idx + 1}|Col{c_idx + 1}: Old[{ov}](int={ot[1]},dec={ot[2]}) " f"vs New[{nv}](int={nt[1]},dec={nt[2]})" )
results["date_diff"] = "OK" if not date_diffs else "\n".join(date_diffs) results["decimal_diff"] = "OK" if not decimal_diffs else "\n".join(decimal_diffs)
content_lookup_diffs = [] if old_size != new_size: logger.info(f"File size differs. Performing content lookup comparison for {os.path.basename(old_file)} ...")
new_file_index = {} for new_line in new_sample: new_parts = new_line.split(new_sep) clean_parts = [part.strip() for part in new_parts] for depth in range(1, len(clean_parts) + 1): prefix_key = tuple(clean_parts[:depth]) new_file_index.setdefault(prefix_key, []).append(new_line)
for old_line in old_sample: old_parts = old_line.split(old_sep) old_key_base = [part.strip() for part in old_parts]
target_new_line = None for depth in range(1, len(old_key_base) + 1): search_key = tuple(old_key_base[:depth]) matches = new_file_index.get(search_key) if matches and len(matches) == 1: target_new_line = matches[0] break
if target_new_line: new_parts = target_new_line.split(new_sep) for c_idx in range(max(len(old_parts), len(new_parts))): ov = old_parts[c_idx] if c_idx < len(old_parts) else "" nv = new_parts[c_idx] if c_idx < len(new_parts) else "" if ov != nv and len(content_lookup_diffs) < 5: content_lookup_diffs.append( f"Key:{old_key_base[0]}|Col{c_idx + 1}:Old[{ov}]->New[{nv}]" ) if content_lookup_diffs: results["content_lookup_diff"] = "\n".join(content_lookup_diffs) else: results["content_lookup_diff"] = "OK (Found but content matches)" else: results["content_lookup_diff"] = "OK"
return results
def _write_result(res, output_path=None): """将结果 JSON 写入指定文件(优先);无路径则回退 stdout(兼容手动调用)""" json_str = json.dumps(res, ensure_ascii=False) if output_path: try: out_dir = os.path.dirname(output_path) if out_dir: os.makedirs(out_dir, exist_ok=True) with open(output_path, 'w', encoding='utf-8') as f: f.write(json_str) f.write('\n') except Exception as e: logger.warning(f"Failed to write result to {output_path}: {e}, falling back to stdout") print(json_str) else: print(json_str)
if __name__ == "__main__": if len(sys.argv) != 5: print("Usage: python data_compare_tool.py <old_file> <new_file> <old_hex_separator> <new_hex_separator>", file=sys.stderr) sys.exit(1) old_f = sys.argv[1] new_f = sys.argv[2] old_hex = sys.argv[3] new_hex = sys.argv[4] output_json_path = os.environ.get('OUTPUT_JSON_PATH') try: res = compare_files(old_f, new_f, old_hex, new_hex) _write_result(res, output_json_path) except Exception as e: logger.error(f"Critical Error processing {old_f}: {e}", exc_info=True) _write_result(_error_result(old_f, "ERROR", e), output_json_path)
|