2

I am writing a script to validate a shapefile.

Here my code:

#-*- coding: UTF-8 -*-

import os
from osgeo import ogr
from PyQt4.QtGui import *
from qgis.core import *
import sys

app = QApplication([])
QgsApplication.setPrefixPath("/usr/", True) # Adjust prefix path according to your installation (see note below)
QgsApplication.initQgis()

class validacaoVetorialMCV(QgsVectorLayer):
    """docstring for Arquivo"""
    def __init__(self, arquivo_shp):
        self.arquivo_shp = arquivo_shp

    def campo_not_null(self, arquivo_shp):

        #Fields to check
        for value in ('geometriaA', 'regime', 'tipoTrecho', 'tipoMassaD', 'tipoLocali', 'jurisdicao', 'administra', 'nivel_1', 'nivel_2', 'nivel_3'):
            idx = arquivo_shp.fieldNameIndex(value);
            values = arquivo_shp.uniqueValues(idx);

            if all(x for x in values) ==  False:
                return 'Registros nulos em %s do: %s' (value, %arquivo_shp.name());


#rootdir = raw_input('Caminho da pasta:')
rootdir = '/home/infra/PycharmProjects/untitled/projeto_desenvolvimento_script/folha_mi_1584_2'
extensions = ('.shp')

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        ext = os.path.splitext(file)[-1].lower()
        #Print all files which have .shp extension
        if ext in extensions:
            #print os.path.join(subdir, file)

            layer = QgsVectorLayer(os.path.join(rootdir, file), file, "ogr")

            #Check if layer was setting
            print layer.name()

            if not layer.isValid():
                print "Layer failed to load!"

            print validacaoVetorialMCV(layer).validar_normalizacao_campo(layer)

Why does my method "campo_not_null" not work? Why did my layer failed to load? Why were other extensions that are not .shp (.gdb, timestamp) read?

Answer in python console:

mi_1584_2_cerrado.shp Layer failed to load! []
mi_1584_2_localidade.shp Layer failed to load! [] 
mi_1584_2_massa_dagua.shp Layer failed to load! [] 
mi_1584_2_trecho_massa_dagua.shp Layer failed to load! [] 
mi_1584_2_trecho_drenagem.shp Layer failed to load! [] 
mi_1584_2_trecho_rodoviario.shp Layer failed to load! [] 
timestamps Layer failed to load! [] 
gdb Layer failed to load! []
  • 1
    Why use pyqgis from outside for that ? There are many other pure Python modules without QGIS. – gene Nov 16 '16 at 16:21
  • Yes, you are right. I began to write this script with pyqgis. So I continued. I thought to learn more about Qgis API. – Diogo Caribé Nov 16 '16 at 17:32
2

I thought to learn more about Qgis API.

Why not use directly the Python console ?

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        if file.endswith(".shp"):
           layer = QgsVectorLayer(os.path.join(rootdir, file), os.path.splitext(file)[0], "ogr")
           layer.isValid()

Works, but if you have subdirectories in rootdir, the layers in the subdirectories are not valid, because of the path os.path.join(rootdir, file)

The solution is to use os.path.join(subdir, file)

class validacaoVetorialMCV(QgsVectorLayer):
    """docstring for Arquivo"""
    def __init__(self, arquivo_shp):
        self.arquivo_shp = arquivo_shp
    def campo_not_null(self):
        for value in ('IDENT','NUM'):
            idx = self.arquivo_shp.fieldNameIndex(value)
            values = self.arquivo_shp.uniqueValues(idx)
            if all(x for x in values) ==  False:
                return (value,layer.name())

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        if file.endswith(".shp"):
            layer = QgsVectorLayer( os.path.join(subdir, file), os.path.splitext(file)[0], "ogr")
            if layer.isValid(): 
               print  validacaoVetorialMCV(layer).campo_not_null()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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