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! []
PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Nov 16, 2016 at 14:05
2
  • 1
    Why use pyqgis from outside for that ? There are many other pure Python modules without QGIS. Commented Nov 16, 2016 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. Commented Nov 16, 2016 at 17:32

1 Answer 1

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()
answered Nov 16, 2016 at 21:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.