0

This should be simple but I could not get it working. I would like to list the files in a directory by excluding files containing a certain pattern using glob.glob in python.

The files in my directory are:

lh.Hip.nii, lh.IPL.nii, lh.LTC.nii, rh.Hip.nii, rh.IPL.nii, rh.LTC.nii

and I would like to list the files by excluding the ones containing "Hip" in the file name:

lh.IPL.nii, lh.LTC.nii, rh.IPL.nii, rh.LTC.nii

There is a similar question glob exclude pattern and the solution only works if I want to exclude files starting with a certain pattern but it does not work in my case.

Any ideas?

Ilkay Isik
  • 203
  • 4
  • 14

2 Answers2

0

You can get all file names with glob then filter them with list comprehension, like so:

[i for i in glob("*.nii") if i.split('.')[1] != 'Hip']
techytushar
  • 673
  • 5
  • 17
  • Thank you so much. This works and for now I am going to use this solution. I am still wondering though whether there is a glob wildcard to do this exclusion. – Ilkay Isik Nov 28 '19 at 16:22
  • @IlkayIsik I read the comments in the link that you mentioned and most of them say that `glob` filter are mostly made for simple inclusion and not exclusion. I also tried some patterns but non of them worked – techytushar Nov 28 '19 at 19:20
0

try this :

result = []
files = glob.glob('*')
for f in files : 
    if 'Hip' not in f : 
        result.append(f)

The result in your case is : ['lh.IPL.nii', 'lh.LTC.nii', 'rh.IPL.nii', 'rh.LTC.nii']

elouassif
  • 308
  • 1
  • 10