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
##Input_Folder=Folder
##nomodeler
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")]
run()
progress.setInfo("Finished")
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"?