Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
spatialthoughts committed Jul 24, 2023
1 parent faf9da1 commit f64b6ba
Show file tree
Hide file tree
Showing 17 changed files with 798 additions and 764 deletions.
168 changes: 92 additions & 76 deletions code/pyqgis/processing/save_attributes_algorithm.py
Original file line number Diff line number Diff line change
@@ -1,76 +1,92 @@
from PyQt5.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterFileDestination)


class SaveAttributesAlgorithm(QgsProcessingAlgorithm):
"""Saves the attributes of a vector layer to a CSV file."""
OUTPUT = 'OUTPUT'
INPUT = 'INPUT'

def initAlgorithm(self, config=None):
self.addParameter(
QgsProcessingParameterFeatureSource(
self.INPUT,
self.tr('Input layer'),
[QgsProcessing.TypeVectorAnyGeometry]
)
)

# We add a file output of type CSV.
self.addParameter(
QgsProcessingParameterFileDestination(
self.OUTPUT,
self.tr('Output File'),
'CSV files (*.csv)',
)
)

def processAlgorithm(self, parameters, context, feedback):
source = self.parameterAsSource(parameters, self.INPUT, context)
csv = self.parameterAsFileOutput(parameters, self.OUTPUT, context)

fieldnames = [field.name() for field in source.fields()]

# Compute the number of steps to display within the progress bar and
# get features from source
total = 100.0 / source.featureCount() if source.featureCount() else 0
features = source.getFeatures()

with open(csv, 'w') as output_file:
# write header
line = ','.join(name for name in fieldnames) + '\n'
output_file.write(line)
for current, f in enumerate(features):
# Stop the algorithm if cancel button has been clicked
if feedback.isCanceled():
break

# Add a feature in the sink
line = ','.join(str(f[name]) for name in fieldnames) + '\n'
output_file.write(line)

# Update the progress bar
feedback.setProgress(int(current * total))

return {self.OUTPUT: csv}

def name(self):
return 'save_attributes'

def displayName(self):
return self.tr('Save Attributes As CSV')

def group(self):
return self.tr(self.groupId())

def groupId(self):
return ''

def tr(self, string):
return QCoreApplication.translate('Processing', string)

def createInstance(self):
return SaveAttributesAlgorithm()
from PyQt5.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingParameterFeatureSource,
QgsProcessingParameterEnum,
QgsProcessingParameterFileDestination,
QgsVectorFileWriter,
QgsWkbTypes,
QgsProject)


class SaveAttributesAlgorithm(QgsProcessingAlgorithm):
"""Saves the attributes of a vector layer to a CSV file."""

def initAlgorithm(self, config=None):
self.addParameter(
QgsProcessingParameterFeatureSource(
'INPUT',
'Input layer',
[QgsProcessing.TypeVectorAnyGeometry]
)
)

# We add a file output of type CSV.
self.addParameter(
QgsProcessingParameterFileDestination(
'OUTPUT',
'Output File',
'CSV files (*.csv)',
)
)

def processAlgorithm(self, parameters, context, feedback):
layer = self.parameterAsVectorLayer(
parameters,
'INPUT',
context)

output = self.parameterAsFileOutput(
parameters,
'OUTPUT',
context)

# Compute the number of steps to display within the progress bar and
# get features from source
total = 100.0 / layer.featureCount() if layer.featureCount() else 0
features = layer.getFeatures()

# Define the options for saving the layer
save_options = QgsVectorFileWriter.SaveVectorOptions()
save_options.driverName = 'CSV'
save_options.fileEncoding = 'UTF-8'

# Create the writer
writer = QgsVectorFileWriter.create(
fileName=output,
fields=layer.fields(),
geometryType=QgsWkbTypes.NoGeometry,
srs=layer.crs(),
transformContext=QgsProject.instance().transformContext(),
options=save_options)


for current, f in enumerate(features):
# Stop the algorithm if cancel button has been clicked
if feedback.isCanceled():
break

# Add a feature in the sink
writer.addFeature(f)

# Update the progress bar
feedback.setProgress(int(current * total))
return {'OUTPUT': output}

def name(self):
return 'save_attributes'

def displayName(self):
return self.tr('Save Attributes As CSV')

def group(self):
return self.tr(self.groupId())

def groupId(self):
return ''

def tr(self, string):
return QCoreApplication.translate('Processing', string)

def createInstance(self):
return SaveAttributesAlgorithm()
4 changes: 0 additions & 4 deletions code/pyqgis/solutions/exercise7.py

This file was deleted.

64 changes: 2 additions & 62 deletions code/pyqgis/solutions/exercise8.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,4 @@
import os
import time

data_dir = os.path.join(os.path.expanduser('~'), 'Downloads', 'pyqgis_masterclass')

layer = iface.activeLayer()
field_names = [field.name() for field in layer.fields()]

# Check if a layer is selected
if not layer:
iface.messageBar().pushMessage('Please select a layer', level=Qgis.Critical)
# Check if the selected layer is a vector layer
if layer.type() != QgsMapLayer.VectorLayer:
iface.messageBar().pushMessage('Please select a vector layer', level=Qgis.Critical)

# Define parameters for QgsVectorFileWriter
output_name = 'output.csv'
output_path = os.path.join(data_dir, output_name)

# We will use QgsVectorFileWriter.create() method
# It takes the following parameters
# fileName: Path to the file
# fields: Fields to write
# geometryType: geometry type of output file
# srs: CRS of the output file
# transformContext: Datum transformation settings
# options: Save Options such as format, encoding etc.

# Define the options for saving the layer
save_options = QgsVectorFileWriter.SaveVectorOptions()
save_options.driverName = 'CSV'
save_options.fileEncoding = 'UTF-8'
# We can also add some format-specific layer options
# These come from GDAL/OGR
# https://gdal.org/drivers/vector/csv.html
save_options.layerOptions = ['SEPARATOR=COMMA']

# Write the file
writer = QgsVectorFileWriter.create(
fileName=output_path,
fields=layer.fields(),
geometryType=QgsWkbTypes.NoGeometry,
srs=layer.crs(),
transformContext=transform_context,
options=save_options)

# Check if we were able to create the writer
if writer.hasError() != QgsVectorFileWriter.NoError:
iface.messageBar().pushMessage(
'Error:', writer.errorMessage, level=Qgis.Critical)

selected_count = layer.selectedFeatureCount()
if selected_count == 0:
iface.messageBar().pushMessage(
'Error:', 'No selected features', level=Qgis.Critical)
else:
for f in layer.selectedFeatures():
writer.addFeature(f)

# delete the writer to flush features to disk
del writer
iface.messageBar().pushMessage(
'Success:',
f'Output file with {selected_count} features written at {output_path}',
level=Qgis.Success)
print(field_names)
64 changes: 64 additions & 0 deletions code/pyqgis/solutions/exercise9.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import os
import time

data_dir = os.path.join(os.path.expanduser('~'), 'Downloads', 'pyqgis_masterclass')

layer = iface.activeLayer()

# Check if a layer is selected
if not layer:
iface.messageBar().pushMessage('Please select a layer', level=Qgis.Critical)
# Check if the selected layer is a vector layer
if layer.type() != QgsMapLayer.VectorLayer:
iface.messageBar().pushMessage('Please select a vector layer', level=Qgis.Critical)

# Define parameters for QgsVectorFileWriter
output_name = 'output.csv'
output_path = os.path.join(data_dir, output_name)

# We will use QgsVectorFileWriter.create() method
# It takes the following parameters
# fileName: Path to the file
# fields: Fields to write
# geometryType: geometry type of output file
# srs: CRS of the output file
# transformContext: Datum transformation settings
# options: Save Options such as format, encoding etc.

# Define the options for saving the layer
save_options = QgsVectorFileWriter.SaveVectorOptions()
save_options.driverName = 'CSV'
save_options.fileEncoding = 'UTF-8'
# We can also add some format-specific layer options
# These come from GDAL/OGR
# https://gdal.org/drivers/vector/csv.html
save_options.layerOptions = ['SEPARATOR=COMMA']

# Write the file
writer = QgsVectorFileWriter.create(
fileName=output_path,
fields=layer.fields(),
geometryType=QgsWkbTypes.NoGeometry,
srs=layer.crs(),
transformContext=transform_context,
options=save_options)

# Check if we were able to create the writer
if writer.hasError() != QgsVectorFileWriter.NoError:
iface.messageBar().pushMessage(
'Error:', writer.errorMessage, level=Qgis.Critical)

selected_count = layer.selectedFeatureCount()
if selected_count == 0:
iface.messageBar().pushMessage(
'Error:', 'No selected features', level=Qgis.Critical)
else:
for f in layer.selectedFeatures():
writer.addFeature(f)

# delete the writer to flush features to disk
del writer
iface.messageBar().pushMessage(
'Success:',
f'Output file with {selected_count} features written at {output_path}',
level=Qgis.Success)
Loading

0 comments on commit f64b6ba

Please sign in to comment.