25

I am writing a shapefile after some processing; however, in the final step I need to do some selection by attributes from the the shapefile.

I am using the command in a shell with the aim of using it in a Python script when it works.

ogr2ogr -f "ESRI Shapefile" -select * where ID="1" outfile.shp infile.shp

I am getting the error message:

FAILURE: 
Unable to open datasource `Downloads' with the following drivers.

What could I be doing wrong?

1
  • Is that really the exact message for that command?
    – BradHards
    Nov 14, 2013 at 10:02

1 Answer 1

41

You miss a minus sign before where and the select is not necessary, so it should be:

ogr2ogr -where ID="1" outfile.shp infile.shp

or if you have to do more complex query on your input data:

ogr2ogr -sql "SELECT * FROM infile WHERE ID='1'" outfile.shp infile.shp

If ID is a field of Integer type, substitute ID='1' with ID=1.

Notes:

  1. If using GDAL < 2.3,-f "ESRI Shapefile" is not necessary because "ESRI Shapefile" is the ogr2ogr default output format; If using GDAL >= 2.3, the format is guessed from the extension.
  2. it's convenient to skip -select and use directly the -where clause when you want to select all the fields.
8
  • 2
    Many thanks it works. I am using: ogr2ogr -where "ID='1'" output.shp input.shp Nov 14, 2013 at 10:12
  • 1
    How can I use this code : ogr2ogr -sql "SELECT * FROM infile WHERE ID='1'" outfile.shp infile.shp" in python? Aug 11, 2016 at 10:50
  • 2
    @ShiuliPervin you can use the statement in python by using os.system('''ogr2ogr ... ''') . be sure to import os at the top of your python script
    – geoeye
    Aug 29, 2016 at 22:08
  • 1
    @afalciano, for the statement ogr2ogr -sql "SELECT * FROM infile WHERE ID='1'" outfile.shp infile.shp instead of just ID=1 is there a way to provide a vector or a set of numbers instead, e.g. ogr2ogr -sql "SELECT * FROM infile WHERE ID IN ['1','5','29']" outfile.shp infile.shp?
    – h.l.m
    May 11, 2017 at 17:16
  • 1
    @h.l.m First question: you have to type numbers as numbers, so your example should be ogr2ogr -sql "SELECT * FROM infile WHERE ID IN [1,5,29]" outfile.shp infile.shp Second question: to get the coordinates of the selected geometry without creating another shp: ogrinfo -sql "SELECT OGR_GEOMETRY FROM infile WHERE ID IN [1,5,29]" infile.shp May 15, 2017 at 8:43

Your Answer

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

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