I have adapted some QGIS pythonscript code from a previous question to assign the filename of a shapefile to that shapefiles attribute table as a prelude to joining multiple shapefiles together (the SAGA plugin isn't working for me). It looks like this:

##Add Filename to Table=name

import os
import glob
from os.path import expanduser
home = expanduser("~")

# Input Folder
#path_dir = home + "/Documents/GIS Data/TEMP/" +  Folder_Name 
path_dir = Input_Folder #This takes the input from the parameter

#Check that the folder "results" exists and if not create it
if not os.path.exists(path_dir + "/Results"):
    os.makedirs(path_dir + "/Results")
    progress.setInfo("Setting save location")
# Set the save location to the folder "results"
    path_res = path_dir + "/Results"

progress.setInfo("Starting file processing")

def run():

#   Set working directory and search for all shapefiles then run algorithm
    os.chdir(path_dir )
    for fname in glob.glob("*.shp"): 

        formula = "'" + fname + "'"
        processing.runalg("qgis:fieldcalculator", fname, 'Filename', 2, 50, 0, True, formula , path_res  + "/"+ fname)

#   Paths of the shapefiles in the Result folder with list comprehension
    output = [shp for shp in glob.glob(path_res + "*.shp")]



Currently it adds the whole filename to the attribute table. How would I alter the formula to trim the filename, for example to extract the OS tile code of a shapefile called "HP_SomeText.shp"?

  • That works perfectly - could have sworn I'd tried that but must have mucked up my quotation marks! Thanks Sep 23, 2015 at 10:27
  • No worries buddy, yeah the quotation marks can be very tricky to get right. Will post the above comment as an answer for the convenience of others :)
    – Joseph
    Sep 23, 2015 at 10:34

1 Answer 1


You can use the following line to get the first two characters of fname and have it inserted into your Attribute Table. Replace your current formula:

formula = "'" + fname + "'"

with this:

formula = "left('" + fname + "',2)"

Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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