3

I have a list of geodataframes which I imported from a folder full of shapefiles:

import glob
import geopandas as gpd
shapefiles = glob.iglob('E:/folder/shapefiles/*.shp')

gdfs = [gpd.read_file(file) for file in shapefiles]

I then clipped them all:

clipped = [gpd.clip(shapefiles, boundary) for shapefiles in gdfs]

Now I need to save each geodataframe (list item) from the list to a shapefile of its correct name in an output folder. I used this code to create another list called filenames of the shapefiles names with the .shp at the end:

filenames = []
for names in items:
    if names.endswith(".shp"):
        filenames.append(names)
print(filenames)

But I dont know how to save each item in the clipped list of geodataframes using its corresponding name from the filenames list

Basically I want to perform this task:

clipped[0].to_file("E:/test_output/"+filenames[0])
clipped[1].to_file("E:/test_output/"+filenames[1])
clipped[2].to_file("E:/test_output/"+filenames[2])

etc etc

But to perform it iteratively and automatically. I need something like this:

for things in clipped:
    things.to_file("E:/test_output"+(for stuff in filenames return filenames[])) 

but with correct syntax and that actually works.

5

Use zip:

import geopandas as gpd
import os

frames = [gpd.read_file(r'C:\GIS\data\testdata\ak_riks.shp'), gpd.read_file(r"C:\GIS\data\testdata\ak_riks_2.shp")]
names = ['r1.shp','r2.shp']

outfolder = r'C:\GIS\data\testdata'

for frame, name in zip(frames, names):
    frame.to_file(os.path.join(outfolder, name))
0

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.