'How to create a loop/function to open set of shapefiles?
How can I create a loop or a function to open many shapefiles at the same time where the names of the shapefiles change very little?
For example with the data below :
a = ("05", "11", "12")
b = ("agglome_a", "piste_c_l", "route_l", "vegetat_a", "batimen_a","route_a_l")
agglo5 = gpd.read_file(f"/content/drive/MyDrive/python/bndt/031H{a[0]}_{b[0]}.shp")
agglo11 = gpd.read_file(f"/content/drive/MyDrive/python/bndt/031H{a[1]}_{b[0]}.shp")
agglo12 = gpd.read_file(f"/content/drive/MyDrive/python/bndt/031H{a[2]}_{b[0]}.shp")
pistec5 = gpd.read_file(f"/content/drive/MyDrive/python/bndt/031H{a[0]}_{b[1]}.shp")
pistec11 = gpd.read_file(f"/content/drive/MyDrive/python/bndt/031H{a[1]}_{b[1]}.shp")
pistec12 = gpd.read_file(f"/content/drive/MyDrive/python/bndt/031H{a[2]}_{b[1]}.shp")
I would imagine a function starting like this :
for i in a:
agglo05 = gpd.read_file(f"/content/drive/MyDrive/python/bndt/031H{i[0:]}_{b[0]}.dbf"
But then ideally add an outcome that would determine a new dataframe. Essentially I would like the function to open all the shapefiles and attributing them a name (ex. agglo5, agglo11, ...).
Solution 1:[1]
I haven't tried,but this may point you in the right direction?
import os
directory = 'files'
for filename in os.listdir(directory):
do something with gpd.read_file(filename)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JoScratcherJo |
