I'm a fairly novice Python user and I've been banging my head against this problem for a number of days now.

Assumptions I've made:

  1. This is doable within QGIS, and does not need to be done externally
  2. The QGIS Expression Editor is sufficient for this task
  3. This task has not been accomplished already by an existing QGIS plugin/function

What I want:

To turn the value returned by the @layer_name QGIS variable into Columns/Rows for a shapefile layer's Attribute table using the data contained in @layer_name to create new columns in the shapefile's attribute table of Continent, Country, State, County, City, Neighborhood filled with the values from the split @layer_name.


@layer_name = "North America-United States-New York-Albany County-Albany-Downtown Albany" (The values in the shapefile's filename are separated by the "-" character. The layout is regular, ie: From beginning to the first "-" is the Continent, between the second/third is Country, etc. This would create a column Continent filled with North America, a column Country filled with United States, etc.)

What I've tried:

left(@layer_name , strpos(@layer_name ,'-')-1)

(This returns the first thing I want, but I've not been able to figure out how to adjust this to be run step by step to get the other things)

What I have now:

from qgis.core import *
from qgis.gui import *
@qgsfunction(args="auto", group='Custom')
def splitfunc(value1):

(This should store the split out values in a list, which is something)

Is this more appropriate for a QGIS Plugin than an Expression?

In a perfect world, this script would be able to be batch-run against many (point shapefile) layers to update them all with the new Column/Row data.

Program that accomplishes a similar goal (Clarification/Inspiration):
MP3Tag does batch transformation of filename to metdata with tokens, allowing people to easily map parts of the filename to the various metadata fields. This is (to me) an identical process in concept, applied to a different type of data.

  • 1
    If you want to create and name new columns programatically, I don't think you could use just the Expression Editor or Field Calculator. A Python custom script would be necessary. – she_weeds Feb 6 '18 at 9:31
  • That makes sense, and refutes one of the assumptions I made above. Going off of your assessment, does the tool need to be a full-blown QGIS Plugin, or would this type of work be appropriate for the Scripts that are in the Processing Toolbox? – Saijin_Naib Feb 6 '18 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.