Search code examples
pythonrecursionglob

using glob.glob recursively while also utilizing .format syntax


This is my first question, and I'm a Python newbie.
Using Python 3.5.

I want to use glob recursively, and found this answer regarding using glob recursively very helpful: Use a Glob() to find files recursively in Python?

However, I also want to utilize a looped variable, and can't seem to figure out the correct syntax. This returns a list just fine:

x = glob.glob(('{0}*.txt').format(some_variable))

This is the "recursive" syntax supplied by the answer to the glob.glob question I linked to, above, which works great and returns a list:

x = glob.glob('**/*.txt', recursive = True)

So far, so good. But when I try this, I get "AttributeError: 'list' object has no attribute 'format'":

x = glob.glob('**/{0}*.txt', recursive = True).format(some_variable)

I also tried this, which gives and "invalid syntax" error:

x = glob.glob(('**/{0}*.txt').format(some_variable)), recursive = True)

I bet I'm getting something wrong in a very basic sense, or perhaps I just can't use .format syntax with the recursive version of glob that I'm trying here? I think there are other ways of doing this recursively, but I still am confused as to why the first syntax I'm trying doesn't work.

Any input is greatly appreciated! Thanks!


Solution

  • Try this:

    x = glob.glob('**/{0}*.txt'.format(some_variable), recursive = True)