Is it possible to calculate the file name in an attribute table?
My shapefile has a name like "cities.shp". In this shapefile I want to have a attribute "cities").
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.Sign up to join this community
You can copy the following script to your QGIS (Processing Toolbox > Scripts > Tools > Create new script). This script takes shapefiles from one folder, uses the Field Calculator algorithm to add the filename as an attribute (with Null values but you can edit this to another expression) and outputs the shapefiles into another folder:
##Test=name import os import glob from os.path import expanduser home = expanduser("~") # Change to match your folder path for shapefiles path_dir = home + "\Desktop\Test\\" path_res = path_dir + "Results\\" def run(): # Set directory and search for all shapefiles then run algorithm os.chdir(path_dir + "Shapefiles\\") for fname in glob.glob("*.shp"): processing.runalg("qgis:fieldcalculator", fname, fname, 2, 99, 0, True, 'NULL' , 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()
There are ways to write attributes to existing shapefiles but I don't have that knowledge yet. Hope this helps!