[GIS] Setting character encoding for all layers at once using PyQGIS

encodingpyqgis

I have to set the character encoding for all layers from system to UTF-8.

Is there a way to change this in all loaded layers at once?

I'm using QGIS 2.8.1 on Windows 7.

Best Answer

You can use the following which should set the encoding of your loaded layers to UTF-8:

Syntax for PyQGIS 2:

for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    layer.setProviderEncoding(u'UTF-8')
    layer.dataProvider().setEncoding(u'UTF-8')
    print layer.name(), layer.dataProvider().encoding()   #Optional check: prints layer name and its encoding source

Syntax for PyQGIS 3:

for layer in QgsProject.instance().mapLayers().values():
    layer.setProviderEncoding(u'UTF-8')
    layer.dataProvider().setEncoding(u'UTF-8')
    print (layer.name(), layer.dataProvider().encoding())

Remember to save your project file (.qgs) afterwards.


Edit:

As suggested by @meles, you can input the above code into the Python Console (Plugins > Python Console; Extensions > Python Console; Ctrl + Alt + P).

Hope this helps!