mail@pastecode.io avatar
a month ago
1.8 kB
from qgis.core import QgsApplication

# Initialize QGIS application (replace 'path/to/qgis' with your actual QGIS path)
qgis_app = QgsApplication([], False)
qgis_app.setPrefixPath('C:\\Program Files\\QGIS 3.34.6', True)

from qgis.core import QgsVectorLayer, QgsCoordinateTransformContext, QgsVectorFileWriter, QgsWkbTypes

# Replace these paths with your input and output file paths
input_layer_path = "C:/Users/matthewh/Documents/Sweep/input_layer.shp"
output_shapefile_path = "C:/Users/matthewh/Documents/Sweep/output_shapefile.shp"

# Load the input vector layer
input_layer = QgsVectorLayer(input_layer_path, "input_layer", "ogr")

# Set up options for writing the vector file
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "ESRI Shapefile"
options.fileEncoding = "UTF-8"
options.overrideGeometryType = QgsWkbTypes.Polygon  # Assuming you want to export polygons
options.skipAttributeCreation = False  # Set to True if you only want to write geometries without attributes
options.onlySelected = False  # Set to True if you want to export only selected features

# Create a QgsCoordinateTransformContext object for handling coordinate transformations if needed
transform_context = QgsCoordinateTransformContext()

# Call the writeAsVectorFormatV3() method to write the layer to the vector file
error_code, error_message, new_file_path, new_layer_name = QgsVectorFileWriter.writeAsVectorFormatV3(
    input_layer, output_shapefile_path, transform_context, options

# Check the error code returned by the method to determine if the write operation was successful
if error_code == QgsVectorFileWriter.NoError:
    print("Vector layer saved successfully!")
    print(f"Error {error_code}: {error_message}")
Leave a Comment