Geographic Information Systems Asked on May 14, 2021
I’m working on a plugin wich works on both QGIS 2 and QGIS 3. This plugin can perform a qgis:splitvectorlayer
if the end user wants to.
As .gpkg
is the default format in QGIS 3 and i don’t want end user to changer their default settings, I want to be able to save splitvectorlayer output as a shape. I just want gpkg files to be converted to shape file in the same folder (p in my code).
I have to use shape format because my plugins relate to a third application that is only compatible with shape files.
couche = self.dlg.mMapLayerComboBox_2.currentText()
champ = self.dlg.mFieldComboBox.currentText()
path = self.get_enregistrement()
p = path + "/" + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "_" + couche + "_" + champ
os.makedirs(p)
split = processing.run("qgis:splitvectorlayer", {'INPUT':self.dlg.mMapLayerComboBox_2.currentText(),'FIELD': self.dlg.mFieldComboBox.currentText(), 'OUTPUT' : p})
split_output = split['OUTPUT']
couches_sep = QgsVectorLayer(split_output, "separation", "ogr")
_writer = QgsVectorFileWriter.writeAsVectorFormat(couches_sep, "UTF-8", "ESRI Shapefile")
After many attempt, this is the only one that doesn’t throw me an error but still i don’t have my gpkg files converted to shape.
So here's the complete code to achieve what I wanted :
couche = self.dlg.mMapLayerComboBox_2.currentText()
champ = self.dlg.mFieldComboBox.currentText()
path = self.get_enregistrement()
p = path + "/" + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + "_" + couche + "_" + champ
os.makedirs(p)
#separation de la couche active par le champ defini au debut du script et enregistrement dans le dossier c:/GeoMCE/nom_de_la_couche_d_origine
split = processing.run("qgis:splitvectorlayer", {'INPUT':self.dlg.mMapLayerComboBox_2.currentText(),'FIELD': self.dlg.mFieldComboBox.currentText(), 'OUTPUT' : p})
def find_files(directory, pattern, only_root_directory):
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename.lower(), pattern):
filename = os.path.join(root, basename)
yield filename
if (only_root_directory):
break
count = 0
for src_file in find_files(p, '*.gpkg', True):
(head, tail) = os.path.split(src_file)
(name, ext) = os.path.splitext(tail)
vlayer = QgsVectorLayer(src_file, name, "ogr")
QgsVectorFileWriter.writeAsVectorFormat(vlayer,p+ "/" + vlayer.name(), 'UTF-8',vlayer.crs(), 'ESRI Shapefile')
output = count
count = 0
for src_file in find_files(p, '*.shp', True):
(head, tail) = os.path.split(src_file)
(name, ext) = os.path.splitext(tail)
vlayer = iface.addVectorLayer(src_file, name, "ogr")
output = count
Answered by Yossarian on May 14, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP