2

I am trying to write a simple script to convert an ESRI geodatabase to a geopackage using gdal/ogr. Here's the example I was using:

from osgeo import ogr

fgdb = r"C:\GIS\data\somefilegeodatabase.gdb"
outdb = r"C:\GIS\data\testdata\OK.gpkg" #Has to be created in advance
fileEncoding = "UTF-8"

driver = ogr.GetDriverByName("OpenFileGDB")
data = driver.Open(fgdb, 0)

#List all layers in the file geodatabase
feature_class_list = []
for i in data:
    foo = i.GetName()
    feature_class_list.append(foo)

#Write to geopackage
for fc in feature_class_list:
    gdbLyr = QgsVectorLayer("{0}|layername={1}".format(fgdb, fc), fc, "ogr")
    print('Writing: ', fc)
    options = QgsVectorFileWriter.SaveVectorOptions()
    options.driverName = "GPKG"
    options.layerName = fc
    options.actionOnExistingFile = QgsVectorFileWriter.CreateOrOverwriteLayer
    options.EditionCapability = 0 #CanAddNewLayer 
    QgsVectorFileWriter.writeAsVectorFormat(gdbLyr, outdb, options) 

Everything works until I get to this line: gdbLyr = QgsVectorLayer("{0}|layername={1}".format(fgdb, fc), fc, "ogr") . This throws an error: NameError: name 'QgsVectorLayer' is not defined I've tried importing in QgsVectorLayer directly from osgeo, but that doesn't work. Has this been deprecated or replaced in osgeo or am I importing it incorrectly?

0

2 Answers 2

5

The osgeo module has never had QgsVectorLayer. That belong to qgis.core module.

https://qgis.org/pyqgis/3.0/core/Vector/QgsVectorLayer.html

1
  • Ugh, thats kinda what I suspected. My example above was from another post I was using as an example (gis.stackexchange.com/questions/372385/…) and there was no mention of it; only a simple import of ogr from osgeo.
    – gwydion93
    Commented Sep 1, 2023 at 12:37
4

As noted in another answer QgsVectorLayer is not and has never been part of the GDAL python bindings.

I think you want gdal.VectorTranslate().

At it's simplest, your code turns into:

from osgeo import gdal

fgdb = r"C:\GIS\data\somefilegeodatabase.gdb"
outdb = r"C:\GIS\data\testdata\OK.gpkg" #Does not need to be created in advance

gdal.VectorTranslate(outdb, fgdb)
1
  • This worked perfectly. Thanks for the concise answer!
    – gwydion93
    Commented Sep 1, 2023 at 18:02

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.