|
2 | 2 | from pathlib import Path |
3 | 3 | from typing import Optional, Union |
4 | 4 |
|
| 5 | +import pandas as pd |
| 6 | + |
5 | 7 |
|
6 | 8 | def should_skip_path(path: Union[str, Path]) -> bool: |
7 | 9 | """ |
@@ -50,3 +52,110 @@ def _find_folder_path(base_path: Path, target_folder_name: str | Path) -> Option |
50 | 52 | return Path(root) / target_folder_name |
51 | 53 |
|
52 | 54 | return None |
| 55 | + |
| 56 | + |
| 57 | +def flexible_data_reader( |
| 58 | + file_path: Union[str, Path], |
| 59 | + separators: Optional[list[str]] = None, |
| 60 | + required_columns: Optional[list[str]] = None, |
| 61 | +) -> pd.DataFrame: |
| 62 | + """ |
| 63 | + Flexible data reader that can handle different file formats and delimiters. |
| 64 | +
|
| 65 | + Tries to intelligently read CSV, TXT, and Excel files by: |
| 66 | + 1. Detecting Excel formats and using pd.read_excel() |
| 67 | + 2. Trying pd.read_csv() with sep=None (auto-detection) using python engine |
| 68 | + 3. Falling back to trying specific separators if provided |
| 69 | +
|
| 70 | + Args: |
| 71 | + file_path: Path to the data file (csv, txt, xlsx, etc.) |
| 72 | + separators: Optional list of separators to try (e.g., [",", "\t", r"\\s+"]) |
| 73 | + If None, uses pandas' auto-detection first |
| 74 | + required_columns: Optional list of column names that must be present |
| 75 | +
|
| 76 | + Returns: |
| 77 | + pd.DataFrame: The loaded dataframe |
| 78 | +
|
| 79 | + Raises: |
| 80 | + FileNotFoundError: If the file does not exist |
| 81 | + ValueError: If the file cannot be parsed or required columns are missing |
| 82 | + """ |
| 83 | + EXCEL_LIKE_EXTENSIONS = {".xlsx", ".xls", ".xlsm", ".xlsb", ".odf", ".ods", ".odt"} |
| 84 | + |
| 85 | + file_path = Path(file_path) |
| 86 | + if not file_path.exists(): |
| 87 | + raise FileNotFoundError(f"File does not exist: {file_path}") |
| 88 | + |
| 89 | + # Handle Excel-like formats |
| 90 | + if file_path.suffix.lower() in EXCEL_LIKE_EXTENSIONS: |
| 91 | + try: |
| 92 | + df_dict = pd.read_excel(file_path, sheet_name=None) |
| 93 | + df = next(iter(df_dict.values())) |
| 94 | + |
| 95 | + if len(df_dict) > 1: |
| 96 | + import warnings |
| 97 | + |
| 98 | + warnings.warn( |
| 99 | + f"Found {len(df_dict)} sheets in {file_path.name}, using only the first one." |
| 100 | + ) |
| 101 | + except Exception as e: |
| 102 | + raise ValueError(f"Failed to read Excel file {file_path}. Error: {e}") from e |
| 103 | + else: |
| 104 | + # Try pandas auto-detection first (works for most well-formed CSV/TSV files) |
| 105 | + try: |
| 106 | + df = pd.read_csv( |
| 107 | + file_path, |
| 108 | + sep=None, # Auto-detect separator |
| 109 | + encoding_errors="backslashreplace", |
| 110 | + engine="python", |
| 111 | + ) |
| 112 | + |
| 113 | + # Check if we got a reasonable result |
| 114 | + if len(df.columns) > 1 and not df.empty: |
| 115 | + # Successfully read with auto-detection |
| 116 | + pass |
| 117 | + else: |
| 118 | + raise ValueError("Auto-detection resulted in single column or empty dataframe") |
| 119 | + |
| 120 | + except Exception as auto_detect_error: |
| 121 | + # If auto-detection fails, try specific separators |
| 122 | + if separators is None: |
| 123 | + separators = [",", "\t", r"\s+", ";"] |
| 124 | + |
| 125 | + df = None |
| 126 | + errors = [] |
| 127 | + |
| 128 | + for sep in separators: |
| 129 | + try: |
| 130 | + df = pd.read_csv(file_path, sep=sep, encoding_errors="backslashreplace") |
| 131 | + |
| 132 | + # Validate we got reasonable data |
| 133 | + if len(df.columns) > 1 and not df.empty: |
| 134 | + break |
| 135 | + else: |
| 136 | + errors.append(f"sep='{sep}': Single column or empty result") |
| 137 | + df = None |
| 138 | + |
| 139 | + except Exception as e: |
| 140 | + errors.append(f"sep='{sep}': {type(e).__name__}") |
| 141 | + continue |
| 142 | + |
| 143 | + if df is None: |
| 144 | + error_summary = "; ".join(errors) |
| 145 | + raise ValueError( |
| 146 | + f"Failed to parse file {file_path}. " |
| 147 | + f"Tried separators: {separators}. " |
| 148 | + f"Errors: {error_summary}. " |
| 149 | + f"Original auto-detect error: {auto_detect_error}" |
| 150 | + ) from auto_detect_error |
| 151 | + |
| 152 | + # Validate required columns if specified |
| 153 | + if required_columns: |
| 154 | + missing_columns = set(required_columns) - set(df.columns) |
| 155 | + if missing_columns: |
| 156 | + raise ValueError( |
| 157 | + f"File {file_path} is missing required columns: {missing_columns}. " |
| 158 | + f"Available columns: {list(df.columns)}" |
| 159 | + ) |
| 160 | + |
| 161 | + return df |
0 commit comments