os.walk(directory) - AttributeError: 'tuple' object has no attribute 'endswith'
<p>I am trying to make a script in python to search for certain type of files (eg: <code>.txt</code>, <code>.jpg</code>, etc.). I started searching around for quite a while (including posts here in SO) and I found the following snippet of code:</p>

<pre><code>for root, dirs, files in os.walk(directory):
    for file in files:
        if file.endswith('.txt'):
            print file
</code></pre>

<p>However, I can't understand why <code>root, dirs, files</code> is used. For example, if I just use <code>for file in os.walk(directory)</code> it throws the error:</p>

<blockquote>
  <p>"AttributeError: 'tuple' object has no attribute 'endswith'".</p>
</blockquote>

<p>What am I missing here?</p>

<p>Thanks in advance!</p>

<p>The reason why you use <code>root, dirs, files</code> with <code>os.walk</code> is described in the <a href="https://docs.python.org/2/library/os.html#os.walk" rel="nofollow">docs</a>:</p>

<blockquote>
  <p>For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).</p>
</blockquote>

<p>so, using <code>root, dirs, files</code> is a Pythonic way of handling this 3-tuple yield.  Otherwise, you'd have to do something like:</p>

<pre><code>data = os.walk('/')
for _ in data:
    root = _[0]
    dirs = _[1]
    files = _[2]
</code></pre>

<p>Tuples don't have an <code>endswith</code> attribute.  Strings, which may or may not be contained in the tuple, do.</p>

python python-3.5 os.walk os.path