Find files in a directory with a partial string match

LearningSlowly picture LearningSlowly · May 24, 2016 · Viewed 28.8k times · Source

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

Answer

Simon Fromme picture Simon Fromme · May 24, 2016

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