0

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)

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Don't use map for a side-effect. The first version is better
@gnibbler Even I was reluctant to add the map solution, but considering the fact that OP wants to remove for, I just added that.
1
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.