Search code examples
python-2.7glob

How to add prefix in glob.glob for path patching


there:

I am trying to use a prefix as a input in glob.glob() function to pull out the png files in my folder. For example: I have dog_1.png, dog_2.png, bird_1.png, bird_2.png in this folder. my input is dog but for some reason, python pulled out nothing. Can you please do me a favor check where I did wrong? Thank you in advance!

dir_name = 'mypath'

if __name__=='__main__':
    prefix = raw_input('Input the prefix of images:')
    files = glob.glob( dir_name + prefix + '*.png')

    print files

What I got is []


Solution

  • Your path to glob is malformed. You'll need to specify your path like this: dir_name/<file>.png (note the forward slash /). You can do this nicely using os.path.join.

    import os
    glob.glob(os.path.join(dir_name, prefix + '*.png'))