Find files in a directory with a partial string match

允我心安 提交于 2020-05-25 05:05:11

问题


I have a directory which contains the following files:

apple1.json.gz
apple2.json.gz
banana1.json.gz
melon1.json.gz
melon2.json.gz

I wish to find all of the apple, banana and melon file types.

From this SO answer I know that I can find by file type by:

import glob, os
os.chdir("/mydir")
for file in glob.glob("*.json.gz"):
    print(file)

However, in my case I can't match by file name or file type. Rather it is a partial file name match (all apple's and so on)

In this SO question, this solution was proposed:

[in] for file in glob.glob('/path/apple*.json.gz'):
    print file

However, this returns zero

[out]
     0

回答1:


Having the files in /mydir as follows

mydir
├── apple1.json.gz
├── apple2.json.gz
├── banana1.json.gz
├── melon1.json.gz
└── melon2.json.gz

you could either do

import glob
import os

os.chdir('/mydir')
for file in glob.glob('apple*.json.gz'):
    print file

or

import glob

for file in glob.glob('/mydir/apple*.json.gz'):
    print file

Changing directories will not effect glob.glob('/absolute/path').




回答2:


Double List Comprehension Method

I was looking for a similar tool and developed a double list comprehension method that should work well for your case (I tested it for my case) ...

import os

def get_file_names_with_strings(str_list):
    full_list = os.listdir("path_to_your_dir")
    final_list = [nm for ps in str_list for nm in full_list if ps in nm]

    return final_list


print(get_file_names_with_strings(['apple', 'banana', 'melon']))


来源:https://stackoverflow.com/questions/37420624/find-files-in-a-directory-with-a-partial-string-match

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!