首页 > 解决方案 > 如何使用python获取文件夹中选定文件的路径?

问题描述

我正在使用glob检索文件夹中所有文件的路径(“数据”):

import glob
import geopandas

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

但是,在这里,我有兴趣知道如何仅检索名称在变量中作为列表列出的选定文件。例如,我只想要以下文件的路径:aaa.txt、bdf.txt、hgr.txt,在“data”文件夹中,它们在变量“imp”中列出。

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

标签: pythonglob

解决方案


像这样的东西可以做到。只需遍历您需要的文件。

import geopandas

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

推荐阅读