简体   繁体   English

Python:Glob.Glob 通配符匹配,遍历通配符列表

[英]Python: Glob.Glob wildcard matching, loop through list for wildcard

I am trying to use the glob.glob wildcard name to pickup files with particular names.我正在尝试使用 glob.glob 通配符名称来拾取具有特定名称的文件。

listing = ['DBMP','CIFP']

for x in range(len(listing)): 
    print(listing[x]) 
       
pklFilenamesList = glob.glob(os.path.join(input_location, '*{x}_.pkl'))

How can I loop through my listing strings and concatenate that with _.pkl files names for my pklFilenamesList variable?如何遍历我的列表字符串并将其与我的 pklFilenamesList 变量的 _.pkl 文件名连接起来?

I want to create a list like so:我想创建一个这样的列表:

*DBMP_.pkl 
*CIFP_.pkl

Update, I am trying to loop through the list like below:更新,我正在尝试遍历列表,如下所示:

pklFilenamesList = glob.glob(os.path.join(input_location, '*{x}_.pkl'))

for filecounter, filename in enumerate(pklFilenamesList):

For the list part, you can easily get the result using a list comprehension with f-string.对于列表部分,您可以使用带有 f 字符串的列表推导轻松获得结果。

newlist = [f'*{x}_.pkl' for x in listing]

['*DBMP_.pkl', '*CIFP_.pkl']

Update更新

To access your file with the given list, you can actually use os.walk and os.path.join to do the work.要使用给定列表访问您的文件,您实际上可以使用os.walkos.path.join来完成这项工作。

for dirpath, dirs, files in os.walk('/'): # / means to check everything throughout your os.
  for filename in files:
    fname = os.path.join(dirpath,filename)
    if fname.endswith('_.pkl'):
        print(fname)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM