Search code examples
pythonglob

How to use glob with a skip list


I am trying to read a file with the same name in a series of directories using glob.glob but I want to skip some specific directories. My directories names are like trj0001,..,trj0099 and I want to skip a list of them like: list = [trj0005, trj0009, trj0011, trj0056, trj0083].

I am currently using this line:

    files = glob.glob(r'my_dir/trj_00*/file.txt')

Any hint is appreciated.


Solution

  • I suggest you to filter the list after using glob, using list comprehension which is quite readable, as follows:

    import glob
    
    files = glob.glob(r'my_dir/trj_00*/file.txt')
    blackList = ['trj0005', 'trj0009', 'trj0011', 'trj0056', 'trj0083']
    files = [f for f in files if all(bl not in f for bl in blackList)]
    
    print(files)