Thursday 21 July 2016

vector - Loading a Shapefile in standalone PyQGIS script


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! []

Answer




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()

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...