-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathraw_loader_exporter.py
More file actions
131 lines (94 loc) · 3.29 KB
/
Copy pathraw_loader_exporter.py
File metadata and controls
131 lines (94 loc) · 3.29 KB
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
# =============================================================================
# RAW DATA LOADER AND EXPORTER
# =============================================================================
from pathlib import Path
import pandas as pd
from typing import Optional, Callable
def load_csv_file(path: Path) -> pd.DataFrame:
return pd.read_csv(path)
def load_parquet_file(
parquet_path: Path,
) -> pd.DataFrame:
return pd.read_parquet(parquet_path, engine="pyarrow")
FILE_LOADERS = {
".csv": load_csv_file,
".parquet": load_parquet_file,
}
def load_logical_table(
base_path: Path,
table_name: str,
log_info: Optional[Callable[[str], None]] = None,
log_error: Optional[Callable[[str], None]] = None,
) -> Optional[pd.DataFrame]:
"""
Load and concatenate all CSV/Parquet files belonging to a logical table.
Files are identified by filename prefix: <table_name>*.csv or <table_name>*.parquet
"""
base_path = Path(base_path)
# List valid files and check format with FILE_LOADERS
files = [
f
for f in base_path.iterdir()
if f.is_file()
and f.name.startswith(f"{table_name}_")
and f.suffix.lower() in FILE_LOADERS
]
if not files:
if log_error:
log_error(f"{table_name}: no files found in {base_path}")
return None
# Prevent mixed file formats
extensions = {f.suffix.lower() for f in files}
if len(extensions) > 1:
raise RuntimeError(f"Mixed file formats detected for {table_name}")
dfs = []
files = sorted(files)
# Route each file using it's format to its registered loader
for file_path in files:
loader = FILE_LOADERS[file_path.suffix.lower()]
try:
df = loader(file_path)
if log_info:
log_info(f"Loaded: {file_path.name} ({len(df)} rows)")
dfs.append(df)
except Exception as e:
if log_error:
log_error(f"Failed loading: {file_path.name}: {e}")
if not dfs:
if log_error:
log_error(f"{table_name}: all matching files failed to load")
return None
return pd.concat(dfs, ignore_index=True)
def export_file(
df: pd.DataFrame,
output_path: Path,
log_info: Optional[Callable[[str], None]] = None,
log_error: Optional[Callable[[str], None]] = None,
index: bool = False,
) -> bool:
"""
Export DataFrame based on file extension (.csv or .parquet).
Returns True if successful, False otherwise.
"""
output_path = Path(output_path)
try:
# Ensure parent directory exists
output_path.parent.mkdir(parents=True, exist_ok=True)
ext = output_path.suffix.lower()
if ext == ".csv":
df.to_csv(output_path, index=index)
elif ext == ".parquet":
df.to_parquet(output_path, index=index, engine="pyarrow")
else:
raise ValueError(
f'Unsupported file extension: "{ext}". ' "Supported: .csv, .parquet"
)
if log_info:
log_info(
f"Exported {ext} file: " f"{output_path.name} " f"({len(df)} rows)"
)
return True
except Exception as e:
if log_error:
log_error(f"Failed to export file {output_path}: {e}")
return False