2

I have in QGIS layer that contains filepath (e.g. D:/file/28238/pic/D4D3-06_1.png) and I would like to get directory path only like D:/file/new/28238/pic.

Is it possible to do by expression in field calculator?

3

There is no builtin function in QGIS field calculator that can do your task, but luckily you can create custom function in QGIS using Function Editor in field calculator, please follow the steps below

  1. Open your shapefile in QGIS.
  2. Open Attribute Table and click field calculator.
  3. Please check the box saying Update existing field and select your desired field.
  4. Then go to Function Editor tab click new file and name it splitLast as shown in figure enter image description here
  5. Repalce the existing code with code shown below

    from qgis.core import *
    from qgis.gui import *
    
    @qgsfunction(args='auto', group='Custom')
    def splitLast(splitStr,splitVal,feature,parent):
       return splitVal.join(splitStr.split(splitVal)[0:-1])
    
  6. click the load button and restart your QGIS now again open the field calculator and you will be able to see your splitLast function in custom list as shown in figure below

enter image description here

  1. Now add the following expression in expression tab and click ok and you are done.

    splitLast("rqewr",'/')
    

Note:Here "rqewr" is the name of field in which "D:/file/28238/pic/D4D3-06_1.png" is stored you can also pass this string instead of field name to function.

Good Luck

  • Cheers Asad! I have also do it by python – seb Jun 11 at 8:00
  • 1
    or more pythonic in a qgsfunction: from pathlib import Path Path('D:/file/28238/pic/D4D3-06_1.png').parent – Jakob Jun 11 at 8:29
1

While waiting I have done it using python:

import os
path=os.path.dirname ("[% "FILEPATH" %]")
os.startfile (path)

Maybe someone will use it... Thanks for your help!

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.