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><code>os.walk()</code> returns a list of results, each of which is itself a tuple.</p>

<p>If you assign a single name to each result, then that name will be a tuple.</p>

<p>Tuples do not have a <code>.endswith()</code> method.</p>

python python-3.5 os.walk os.path