From a1daa619de461c64bcad30c44ee1197828698a66 Mon Sep 17 00:00:00 2001 From: nixevol Date: Mon, 21 Sep 2026 10:00:44 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=9B=9E=E5=86=99=E6=B8=85=E6=B4=97?= =?UTF-8?q?=E5=90=8E=E7=9A=84=E6=A5=BC=E5=AE=87=E7=BB=93=E6=9E=9C=20CSV?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- marketgrid/nrdata.py | 11 ++++++++++- tests/test_nrdata.py | 4 ++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/marketgrid/nrdata.py b/marketgrid/nrdata.py index ae87c65..658df11 100644 --- a/marketgrid/nrdata.py +++ b/marketgrid/nrdata.py @@ -30,7 +30,8 @@ def build_gpkg(data_csv, polygon_csv, output_path): except Exception: continue if not geometry.is_empty and geometry.is_valid: polygons.setdefault(str(row["building_id"]), geometry) - with data_csv.open(encoding=_encoding(data_csv), newline="") as f: + data_encoding = _encoding(data_csv) + with data_csv.open(encoding=data_encoding, newline="") as f: reader = csv.DictReader(f) fields = [x for x in (reader.fieldnames or []) if x not in DROP_COLUMNS] if "building_id" not in fields: raise ValueError("楼宇结果 CSV 缺少 building_id 字段") @@ -40,6 +41,14 @@ def build_gpkg(data_csv, polygon_csv, output_path): geometry=polygons.get(str(row.get("building_id", "")).strip()) if not geometry or (row.get("查询状态", "").strip() and row.get("查询状态", "").strip() not in {"成功", "命中"}): continue clean={x:row.get(x, "") for x in fields if x != "WKT"}; clean["WKT"]=geometry.wkt; rows.append((clean,geometry)) + # 先原子回写清洗后的 CSV,避免中途失败破坏原文件。 + temporary_csv = data_csv.with_name(f".{data_csv.name}.tmp") + with temporary_csv.open("w", encoding=data_encoding, newline="") as f: + writer = csv.DictWriter(f, fieldnames=fields) + writer.writeheader() + writer.writerows(clean for clean, _ in rows) + temporary_csv.replace(data_csv) + output_path.parent.mkdir(parents=True, exist_ok=True) if output_path.exists(): output_path.unlink() conn=sqlite3.connect(output_path) diff --git a/tests/test_nrdata.py b/tests/test_nrdata.py index 25c3491..6828bb7 100644 --- a/tests/test_nrdata.py +++ b/tests/test_nrdata.py @@ -25,6 +25,10 @@ class NrDataTest(unittest.TestCase): writer.writerow(["2", "A", "失败", "超时", ""]) result = build_gpkg(data, polygon, output) self.assertEqual(result["feature_count"], 1) + with data.open(encoding="gbk", newline="") as stream: + cleaned = csv.DictReader(stream) + self.assertEqual(cleaned.fieldnames, ["building_id", "building_name", "WKT"]) + self.assertEqual(len(list(cleaned)), 1) conn = sqlite3.connect(output) try: columns = [row[1] for row in conn.execute('pragma table_info("NRBuildingsData")')]