Search code examples
pythonglob

List of files (which might contain wildcards) as arguments of a Python script


In many python scripts I find my self doing the following:

for maybe_glob in sys.argv[1:]:
    for filename in glob.iglob(maybe_glob):
        print(filename)

I have to do this because the scripts need to also run in terminals that do not expand wildcards (such as windows). Is there shorter version for this? Is there a way (for example with argparser) to directly expand wildcards during argument parsing?

Thanks


Solution

  • You could avoid the double loop with a chaining iterator, but it hardly seems like an improvement.

    for fname in itertools.chain(*map(glob.iglob, sys.argv[1:])):
        print fname
    

    But you could wrap it into a routine:

    def allglob(args):
        return itertools.chain.from_iterable(map(glob.iglob, args))