Tuesday, 11 August 2015

python - Force OGR to use specific driver for input format


How could one force to use a specific format to read input files?


Out of the box ogr2ogr automatically chooses from it's long list of formats, which most of the time is great. However today I'm troubleshooting data files which won't convert, but should, and I'm trying to get to the bottom of why. Knowing with confidence that ogr2ogr is using the correct driver and not picking the wrong driver(s) would be a great aid in that process.


A conversation on Freenode indicated OGR_SKIP config option might be one way (the only?), but I've not been able to concoct a working incantation yet.


Both command line ogr2ogr and python solutions are welcome.



Answer



A python solution is fairly simple using ogr.GetDriverByName(in_format).Open(in_file).



import sys
from osgeo import ogr
def main(in_file, in_format, out_file, out_format):
in_ds = ogr.GetDriverByName(in_format).Open(in_file)
out_ds = ogr.GetDriverByName(out_format).CopyDataSource(in_ds, out_file)

if __name__ == '__main__':
main(*sys.argv[1:])

To take care of the CSV special case (see comments) without changing the input filename format:



def main(in_file, in_format, out_file, out_format):
if in_format == 'CSV' and in_file[-3:].lower() != 'csv':
in_file = 'CSV:' + in_file
in_ds = ogr.GetDriverByName(in_format).Open(in_file)
out_ds = ogr.GetDriverByName(out_format).CopyDataSource(in_ds, out_file)

If you want to stick with the command line ogr2ogr, it's useful to know that the order that drivers are listed in ogrinfo --formats is the order in which they are tried, so you can limit the number of drivers you have to specifiy with OGR_SKIP.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...