Count all files in all folders/subfolders with Python
<p>Which is the <strong>most efficient way</strong> to count all files in all folders and subfolders in Python? I want to use this on Linux systems.</p>

<p>Example output:</p>

<blockquote>
  <p>(Path files)</p>
  
  <p>/ 2</p>
  
  <p>/bin 100</p>
  
  <p>/boot 20</p>
  
  <p>/boot/efi/EFI/redhat 1</p>
  
  <p>....</p>
  
  <p>/root 34</p>
  
  <p>....</p>
</blockquote>

<p>Paths without a file should be ignored.</p>

<p>Thanks.</p>

<pre><code>import os

print [(item[0], len(item[2])) for item in os.walk('/path') if item[2]]
</code></pre>

<p>It returns a list of tuples of folders/subfolders and files count in <code>/path</code>.</p>

<p>OR</p>

<pre><code>import os

for item in os.walk('/path'):
    if item[2]:
        print item[0], len(item[2])
</code></pre>

<p>It prints folders/subfolders and files count in <code>/path</code>.</p>

<p>If you want try faster solution, then you had to try to combine:</p>

<pre><code>os.scandir() # from python 3.5.2
</code></pre>

<p>iterate recursively and use:</p>

<pre><code>from itertools import count

counter = count()
counter.next() # returns at first 0, next 1, 2, 3 ...

if counter.next() &gt; 1000:
    print 'dir with file count over 1000' # and use continue in for loop
</code></pre>

<p>Maybe that will be faster, because I think in <code>os.walk</code> function are unnecessary things for you.</p>

python linux file count