Gun
Gun

Reputation: 576

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']

Upvotes: 0

Views: 205

Answers (2)

Sandsten
Sandsten

Reputation: 757

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}')

Upvotes: 1

Tim Roberts
Tim Roberts

Reputation: 54668

Like this?

import geopandas

path = "/home/data/"
imp = [ 'aaa.txt', 'bdf.txt', 'hgr.txt']
for file in imp:
    if os.path.exists(path+file):
        sf = geopandas.read_file(path+file)

Upvotes: 0

Related Questions