0

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, ...).

  • can you use a dictionary to hold the file contents? – Michael Delgado Apr 22 '22 at 17:01
  • Does this answer your question? [Using a loop to create and assign multiple variables (Python)](https://stackoverflow.com/questions/41645898/using-a-loop-to-create-and-assign-multiple-variables-python) – Michael Delgado Apr 23 '22 at 00:45
  • Thank you for the answer! I am a beginner and still trying to figure out how to apply that code to my files... – Amélie Apr 27 '22 at 20:10

1 Answers1

0

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)