0

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

4
  • so you are basically looking for r"/home/data/aaa.txt", r"/home/data/bdf.txt" and r"/home/data/hgr.txt"? If yes, why you need the glob then? Commented Nov 5, 2021 at 19:04
  • Actually, there are hundreds of such files of interest, not just three, that have to be chosen from thousands of files in a folder. Commented Nov 5, 2021 at 19:05
  • Ok then you are looking for files like aaa.txt? Is it like *aaa.txt or *aaa*.txt? Commented Nov 5, 2021 at 19:07
  • Files' name does not follow any pattern. Instead, I want to read the path of all files whose names are available as a list stored in a variable "imp". Commented Nov 5, 2021 at 19:09

2 Answers 2

1

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}')
Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately I cannot edit the answer since it's smaller then 6 characters. Your quote sign is in wrong place. f"/home/data/"{file}
@MSH I was able to fix it.
Ah sorry, my mistake.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.