diff --git a/imod/msw/meteo_mapping.py b/imod/msw/meteo_mapping.py index 28efa0a5e..9e40d580f 100644 --- a/imod/msw/meteo_mapping.py +++ b/imod/msw/meteo_mapping.py @@ -47,11 +47,14 @@ def open_first_meteo_grid(mete_grid_path: str | Path, column_nr: int) -> xr.Data with open(mete_grid_path, "r") as f: lines = f.readlines() - potential_paths = [line.split(",")[column_nr].replace('"', "") for line in lines] - for potential_path in potential_paths: - if _is_parsable_and_existing_path(potential_path, mete_grid_path): - resolved_path = mete_grid_path / ".." / Path(potential_path) - return imod.rasterio.open(resolved_path) + potential_paths = [] + for line in lines: + cols = line.strip().split(",") + if len(cols) > column_nr: + potential_paths.append(cols[column_nr].replace('"', "")) + if _is_parsable_and_existing_path(potential_paths[-1], mete_grid_path): + resolved_path = mete_grid_path / ".." / Path(potential_paths[-1]) + return imod.rasterio.open(resolved_path) error_message = dedent(f""" Did not find parsable path to existing .ASC file in column {column_nr}. Got diff --git a/imod/tests/test_msw/test_meteo_grid.py b/imod/tests/test_msw/test_meteo_grid.py index 9f93d8ec0..76ddfe0cd 100644 --- a/imod/tests/test_msw/test_meteo_grid.py +++ b/imod/tests/test_msw/test_meteo_grid.py @@ -11,6 +11,7 @@ from numpy.testing import assert_equal from imod.msw import MeteoGrid, MeteoGridCopy +from imod.msw.meteo_mapping import open_first_meteo_grid from imod.util.regrid import RegridderWeightsCache @@ -21,7 +22,7 @@ def test_meteo_grid_init(meteo_grids): assert meteo_grids.dataset["evapotranspiration"].dims == ("time",) -def test_meteo_grid_write(meteo_grids): +def test_meteo_grid_write_read(meteo_grids): meteo_grid = MeteoGrid(*meteo_grids) with tempfile.TemporaryDirectory() as output_dir: @@ -33,6 +34,19 @@ def test_meteo_grid_write(meteo_grids): ) gridnames = sorted([file.name for file in output_dir.glob("meteo_grids/*.asc")]) + # test reading as well : roundtrip + with open(output_dir / "mete_grid.inp") as fin: + lines = fin.readlines() + lines.insert( + -1, " " + ) # add an empty line to test robustness of the parser to empty lines + lines.append(" ") + with open(output_dir / "mete_grid.inp", "w") as fout: + fout.writelines(lines) + open_first_meteo_grid( + output_dir / "mete_grid.inp", 2 + ) # only test parsing of the mete_grid.inp file + expected_paths = [ '"meteo_grids' + os.path.sep + 'precipitation_20000101000000.asc"', '"meteo_grids' + os.path.sep + 'precipitation_20000102000000.asc"',