GDAL VectorTranslate – How to Preserve ID Field When Using osgeo/ogr/gdal VectorTranslate Function in Python

exportgdalogrosgeopython

When using the Python osgeo/gdal/ogr library, how can I force the feature ID column (e.g., "OBJECTID" or "FID" columns) to be preserved in the output file?

I thought I would just need to use the "-preserve_fid" option/flag, but it just doesn't seem to be working.

Here's what I've got so far:

# Importing main libraries
import os
from osgeo import ogr
from osgeo import gdal

# Use OGR specific exceptions
ogr.UseExceptions()
gdal.UseExceptions() 

# Definitions for input data
inDriverName = "OpenFileGDB"
inGDBPath = 'path/to/input.gdb'
inLayerName = 'input_layer_name'

inDriver = ogr.GetDriverByName(inDriverName)
inDataSource = inDriver.Open(inGDBPath, 0)
inLayer = inDataSource.GetLayerByName(inLayerName)
inLayerIDColname = inLayer.GetFIDColumn()
inlayerDefinition = inLayer.GetLayerDefn()
inLayerColNames = [inlayerDefinition.GetFieldDefn(i).GetName() for i 
                   in range(inlayerDefinition.GetFieldCount())]]

# Definitions for output data
outCSVPath = 'path/to/output.csv'
outDriverName = 'CSV'

outDriver = ogr.GetDriverByName(outDriverName)


# Remove output CSV if it already exists
if os.path.exists(outCSVPath):
    outDriver.DeleteDataSource(outCSVPath)

# Establishing the VectorTranslateOptions
gdoptions=gdal.VectorTranslateOptions(options=['-lco','GEOMETRY=AS_WKT',
                                               '-preserve_fid',],
                                      format=outDriverName,
                                      layers=[inLayerName])

# Executing the VectorTranslate command
ds = gdal.VectorTranslate(destNameOrDestDS=outCSVPath, 
                          srcDS=inGDBPath, 
                          options=gdoptions)

# Releasing the data
ds = None

Note that the code above does indeed include the -preserve_fid option.

However, when I use this script to export a specific layer inside a GDB, the FIDs are not included in the newly-generated CSV file.

Is there anything missing in my input above?

Best Answer

You need to add a special SQLStatement keyword in the VectorTranslateOptions:

gdoptions=gdal.VectorTranslateOptions(options=['-lco','GEOMETRY=AS_WKT',
                                               '-preserve_fid',],
                                      format=outDriverName,
                                      SQLStatement=f'select {inLayerIDColname} as {inLayerIDColname}, * from {inLayerName}',
                                      SQLDialect='OGRSQL',
                                      layers=[inLayerName])