2

I am trying to import a geojson file of county in U.S. and editing it. Using the following code, I can get a features of the state (in this case "Missouri").

My question is when I edit the layer, features in the original file ("county.json") are also deleted. To avoid this, how should I do?

QgsProject.instance().clear()

county = QgsVectorLayer('[some path]/county.json',
                        'county', 
                        'ogr')

QgsProject.instance().addMapLayer(county)

with edit(county):
    request = QgsFeatureRequest().setFilterExpression('"STATE"!=\'%s\'' % 29)
    request.setSubsetOfAttributes([])
    request.setFlags(QgsFeatureRequest.NoGeometry)
    for f in county.getFeatures(request):
        county.deleteFeature(f.id())
hiroaki
  • 187
  • 7
  • 1
    What behavior do you expect? By editing a layer it seems normal to me that the file is updated accordingly. – YoLecomte Apr 17 '20 at 18:03
  • My expectation is that I would like to preserve the original file because I would like to use the original file several times.

    For example, the first algorithm use the intersection between Missouri and rivers and the second algorithm use the intersection between Illinois and rivers.

    When we use "pandas" in python, we use a data frame by reading a CSV file and manipulate the data frame, but the CSV file does not change. I would expect to get such a behavior.

    – hiroaki Apr 17 '20 at 18:43
  • In which case you need to copy the feature to a new file rather than deleting the other features – Ian Turton Apr 17 '20 at 19:03

1 Answers1

3

Based on the comment, I found the solution: Duplicating layer in memory using pyqgis?

QgsProject.instance().clear()

county = QgsVectorLayer('[some path]/county.json',
                        'county', 
                        'ogr')

feats = [feat for feat in county.getFeatures()]

mem_layer = QgsVectorLayer("Polygon?crs=epsg:4326", 
                           "mem_layer", 
                           "memory")

mem_layer_data = mem_layer.dataProvider()
attr = county.dataProvider().fields().toList()
mem_layer_data.addAttributes(attr)
mem_layer.updateFields()
mem_layer_data.addFeatures(feats)
QgsProject.instance().addMapLayer(mem_layer)

with edit(mem_layer):
    request = QgsFeatureRequest().setFilterExpression('"STATE"!=\'06\'')
    request.setSubsetOfAttributes([])
    request.setFlags(QgsFeatureRequest.NoGeometry)
    for f in mem_layer.getFeatures(request):
        mem_layer.deleteFeature(f.id())
hiroaki
  • 187
  • 7