Python os.walk() method
<p>I am new to stackoverflow. I have taken lot of help from this forum in writing the following code. The code below searches all directories/sub directories on the system drives but while looking into 'D' drive, it looks only those directories and sub directories that are after the folder in which i run this program. </p>

<p>I mean if I run this program from <code>D:\Dir1\Dir2\Dir3\myCode.py</code>, it will search directories and sub directories after <code>D:\Dir1\Dir2\Dir3\</code> not the entire 'D' drive. It works good with other drives while running from the same location. This is my code:</p>

<pre><code>import os, string
total=0
for driveLetter in string.ascii_uppercase:
    try:
        if os.path.exists(driveLetter+':'):
            for root, dirs, docs in os.walk(top=driveLetter+':', topdown=True):            
                for name in docs:
                    try:
                        if (name.endswith(".docx")) or (name.endswith(".doc")):
                            print(os.path.join(root, name))
                            total+=1                          
                    except:
                        continue
    except:
        continue
print ('You have a total of ' + str(total) + ' word documents in your System')
</code></pre>

<p>In Windows <a href="http://superuser.com/questions/135214/using-cd-command-in-windows-command-line-cant-navigate-to-d">each process may set a current working directory on each <em>drive</em> separately</a>. <code>D:</code> means the <em>current working directory</em> on drive D. Here the behaviour occurs, because on all other drives the current working directory is set to the root directory, but on <code>D:</code> it is the <code>D:\Dir1\Dir2\Dir3\</code> because the working directory was changed to the location of the script. To refer to the <em>root</em> directory of <code>D:</code> unambiguously, you need to use <code>D:\</code>. Thus</p>

<pre><code>drive_root = drive_letter + ':\\'  # double \\ because this is a Python string literal
if os.path.exists(drive_root):
    for root, dirs, docs in os.walk(drive_root, topdown=True):            
</code></pre>

python