0

I've successfully used the Python script written by ndawson as a reply to the following question:

Creating points along line according to attribute data using QGIS?

After I changed my QGIS version from 2.18 to 3.4 Madeira, I receive the following error message after line num_points = feat['num_points']:

  File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\code.py", line 63, in runsource
    code = self.compile(source, filename, symbol)
  File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\codeop.py", line 168, in __call__
    return _maybe_compile(self.compiler, source, filename, symbol)
  File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\codeop.py", line 99, in _maybe_compile
    raise err1
  File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\codeop.py", line 87, in _maybe_compile
    code1 = compiler(source + "\n", filename, symbol)
  File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\codeop.py", line 133, in __call__
    codeob = compile(source, filename, symbol, self.flags, 1)
  File "<input>", line 6
    num_points = feat['num_points']
             ^
SyntaxError: invalid syntax

When I change the name num_points to something else, I receive a different error message:

  File "C:\PROGRA~1\QGIS3~1.4\apps\Python37\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
NameError: name 'feat' is not defined

As you can see, I don't know Python at all.

Can someone help me solving this issue?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
mia03
  • 9
  • 1

1 Answers1

2

Try this one, I've made some changes to the original script from Nyall Dawson due to new or depreciated classes in QGIS3:

from qgis.core import QgsFeature, QgsVectorFileWriter, QgsGeometry, QgsWkbTypes

def create_points(feat,writer):
    geometry = feat.geometry()
    if not geometry:
        return
    length = geometry.length()
    # -----------------
    # change 'num_points' to match your field name for the number of points field
    # -----------------
    num_points = feat['num_points']
    delta = length / ( num_points + 1.0 )
    distance = 0.0
    for i in range(num_points):
        distance += delta
        output_feature = QgsFeature(feat)
        output_feature.setGeometry( geometry.interpolate(distance) )
        writer.addFeature(output_feature)

layer = iface.activeLayer()

# ---------------
# change 'd:/test_points.shp' to desired output file name
# ---------------

writer = QgsVectorFileWriter('d:/test_points.shp',None, layer.fields(), QgsWkbTypes.Point, layer.crs(),"ESRI Shapefile")

for f in layer.getFeatures():
    create_points(f,writer)

del writer
Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
eurojam
  • 10,762
  • 1
  • 13
  • 27