简体   繁体   中英

python glob exclude pattern in the file name

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?

您可以使用glob获取所有文件名,然后使用列表理解过滤它们,如下所示:

[i for i in glob("*.nii") if i.split('.')[1] != 'Hip']

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM