I have a number of shapefiles (protected areas for different years) which I would like to dissolve using one attribute. I have not found a line of code to create a list from the shapefiles so iterate through all of them at once.

My files:

#files to create a list from 
wdpa95 = gpd.read_file('.../wdpa95_uk_terr.shp')
wdpa99 = gpd.read_file('.../wdpa99_uk_terr.shp')
wdpa03 = gpd.read_file('.../wdpa03_uk_terr.shp')
wdpa07 = gpd.read_file('.../wdpa07_uk_terr.shp')
wdpa11 = gpd.read_file('.../wdpa11_uk_terr.shp')
wdpa15 = gpd.read_file('.../wdpa15_uk_terr.shp')

#dissolve wdpa datasets to create single layer
wdpa95 = gpd.read_file('.../wdpa95_uk_terr.shp')
wdpa95 = wdpa95[['ISO3', 'geometry', 'PA_DEF', 'STATUS_YR']]
wdpa95_dissolve = wdpa95.dissolve(by = 'PA_DEF', aggfunc = 'max')

I could manually go through the shapefiles one by one but I figured there should a smarter way to create a list and iterate the dissolve process.


I assume that all shapefiles include these attributes: ISO3, geometry, PA_DEF, STATUS_YR

import os
from glob import glob
import geopandas as gpd

# get list of .shp file names in shp_folder
shp_folder = "folder_path"
shp_files = glob.glob(shp_folder + "/*.shp")

# OR create your own list of file names
# shp_files = ['.../wdpa95_uk_terr.shp', '.../wdpa99_uk_terr.shp', ....]

for file_name in shp_files:
    wdpa = gpd.read_file(file_name)
    wdpa = wdpa[['ISO3', 'geometry', 'PA_DEF', 'STATUS_YR']]
    wdpa_dissolve = wdpa.dissolve(by='PA_DEF', aggfunc='max')

    new_file_name = file_name[:6] + "_dissolve.shp" # wdpa95_dissolve.shp
    # OR 
    # new_file_name = file_name[:-4] + "_dissolve.shp" # wdpa95_uk_terr_dissolve.shp

    new_file_path = os.path.join(shp_folder, new_file_name)

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.