2

I wanto to build a function (let's call it clip) that accepts a vector-file (can be a shapefile, a geopackage....) and a raster. How can I make sure the argument that the users gives to the function is a type that for example gepandas can read? I though about something like (completey pseudocode):

def clip(shape, raster):
    if driver(shape) not in geopandas.drivers:
        raise TypeError
    else:
        clip(raster, shape)

I know this is kind of random pseudocode, but maybe some understand what I mean and has an idea.

When I try:


import geopandas

shape = "no_shape.sph"

try:
    shape = geopandas.read_file(shape)
except CPLE_OpenFailedError:
    print("that's not a the path to a vector geometry")
except DriverError:
    print("that's not a valid vector geometry")

I get:

CPLE_OpenFailedError                      Traceback (most recent call last)

fiona/_shim.pyx in fiona._shim.gdal_open_vector()

fiona/_err.pyx in fiona._err.exc_wrap_pointer()

CPLE_OpenFailedError: no_shape.sph: No such file or directory


During handling of the above exception, another exception occurred:

DriverError                               Traceback (most recent call last)

<ipython-input-17-7ed5ed6090fb> in <module>
      5 try:
----> 6     shape = geopandas.read_file(shape)
      7 except CPLE_OpenFailedError:

And I have no idea how to catch that exception and print a message that this is no valid shape (or any other vector supported by geopandas).

2
  • do you like to check if geopandas can read some kind of file or if the geometries inside the file are valid (e.g. in sense of OGC standards)?
    – Mesa
    Commented Jan 25, 2020 at 17:02
  • The first part actually. If geopandas can read some kind of file;) Commented Jan 25, 2020 at 17:15

1 Answer 1

2

How about something like this,

try:
    gdf = geopandas.read_file(shape)
except DataIOError as err:
    # log error if you want
    # log(str(err))
    raise TypeError
clip(raster, shape)

Good all try/except

Edit: Just to add some links fiona open doc, geopandas read_file is based on fiona open geopandas io doc.

1
  • sounds great!! I'll give it a shot:) thanks!! Commented Jan 25, 2020 at 18:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.