Is there any way to extract the encoding, like utf8, from a shapefile?

I want to be able to write a script that enables the user to import shapefiles without having to worry about which encoding the file. I'm using shp2pgsql but here I have to specify which encoding to import with...

I have a script that's written in SQL using gdal-tools. I would like to extend the script with either:

  1. somehow extracting the encoding of the shapefile to be able to use shp2pgsql to import or,

  2. is there some way to magically say "import with the encoding that is set in the file"?

I'm no programmer at heart, mearly faking it with SQL...

  • 2
    There is no set way to define the encoding. Esri now creates a .cpg suffix file, but it's neither required nor used by all shapefile readers.
    – Vince
    Commented Feb 22, 2018 at 14:16
  • in R i do this: library(readr) guess_encoding("smn.conagua.gob.mx/tools/RESOURCES/Diarios/15021.txt")
    – Elio Diaz
    Commented Feb 22, 2018 at 16:01

1 Answer 1


Assuming you are using PyQGIS, you can get it like this:

layer = iface.activeLayer()

Sample results with a few shapefiles I tested:


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.