Search code examples
pythonoperating-systemglob

How can I get a list of all files by exclude a string?


I have a folder full of files:

aaa.sh
bbb.sh
ccc.sh
aaadomain.sh
hhhdomain.sh
yyyydomain.sh
aaadomainasssa.sh

When I do this, I get the list of all files

import glob,os
filelist = glob.glob('*.sh')

But, how can I exclude all files that have domain as a String in the filename?


Solution

  • Use a filter if you're planning to iterate over filelist:

    for f in filter(lambda x: 'domain' not in x, glob.glob('*.sh')):
        ... # do something with f
    

    Alternatively, use a list comprehension:

    filelist = [x for x in glob.glob('*.sh') if 'domain' not in x]