From 8d523bfc1126572ec62d5cdfd0b0ac07d309b065 Mon Sep 17 00:00:00 2001 From: Alireza Adli Date: Sun, 25 Feb 2024 22:47:20 -0500 Subject: [PATCH] Add deleting a field as a new service --- .gitignore | 1 + services_scripts/delete_field.py | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 services_scripts/delete_field.py diff --git a/.gitignore b/.gitignore index f67afeb..01cbcbc 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ standalone_charm.py # Other Files setting_up_standalone_pyqgis.docx +symbology-style.db .idea/.name diff --git a/services_scripts/delete_field.py b/services_scripts/delete_field.py new file mode 100644 index 0000000..3ba3401 --- /dev/null +++ b/services_scripts/delete_field.py @@ -0,0 +1,41 @@ +from qgis.core import QgsApplication, QgsVectorLayer, QgsProject, edit +from qgis.analysis import QgsNativeAlgorithms + + +def load_layer(path, layer_name): + the_layer = QgsVectorLayer(path, layer_name, "ogr") + if not the_layer.isValid(): + print(f'{layer_name} failed to load!') + else: + QgsProject.instance().addMapLayer(the_layer) + return the_layer, layer_name + + +# Set the path to QGIS installation +QgsApplication.setPrefixPath("C:/Program Files/QGIS 3.34.1/apps/qgis", True) + +# Initialize QGIS application +qgs = QgsApplication([], False) +qgs.initQgis() + +# Add native algorithms provider +QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) + +layer_path = 'C:/Users/a_adli/PycharmProjects/hydroquebec_archetype_gispy/data/aEndeavor/merged_all_delete_columns/merge_divisions.shp' +the_layer = load_layer(layer_path, 'Merged Pairwise Clipped')[0] + +column_name = "layer" # and 'path' + +# Start editing +with edit(the_layer): + # Get the index of the column to delete + idx = the_layer.fields().indexFromName(column_name) + + # Delete the field + the_layer.deleteAttribute(idx) + + # Update layer fields + the_layer.updateFields() + + +qgs.exitQgis() \ No newline at end of file