user765443
user765443

Reputation: 1892

loop in 2-dimension array in Python(list)

I am searching one particular pattern and remove the File. I have written following code and it is working file but I feel I can reduce for loop when I am trying to remove File (except List comprehension)

rm_file_pat = ["*.abc*", "*.xyz"]
        rm_file_list = [ glob.glob(f_pat) for f_pat in rm_file_pat]
        for rm_file in rm_file_list:
            for _rm_file in rm_file:
                os.remove(_rm_file)

Upvotes: 0

Views: 88

Answers (2)

John La Rooy
John La Rooy

Reputation: 304137

from glob import glob
rm_file_pat = ["*.abc*", "*.xyz"]
for rm_file in (fn for f_pat in rm_file_pat for fn in glob(f_pat))
    os.remove(rm_file)

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239443

You can flatten the rm_file_list using chain.from_iterable and then simply iterate over the list

import itertools
for rm_file in itertools.chain.from_iterable(rm_file_list):
    os.remove(rm_file)

Upvotes: 1

Related Questions