How to get path of selected files in a folder using python?

I am using glob to retrieve the path of all files in a folder ("data"):

import glob
import geopandas

for file in glob.glob(r"/home/data/*.txt"):
    sf = geopandas.read_file(file)

However, here, I am interested in knowing how to retrieve only selected files whose names are listed in a variable as a list. For instance, I want the path of only the following files: aaa.txt, bdf.txt, hgr.txt, in the "data" folder, which are listed in variable "imp".

imp = ['aaa.txt', 'bdf.txt', 'hgr.txt']

>Solution :

Something like this could do it. Just loop through the files you need.

import geopandas

imp = ['aaa.txt', 'bdf.txt', 'hgr.txt']
for file in imp:
    sf = geopandas.read_file(f"/home/data/{file}")

Leave a Reply