Timi
Timi

Reputation: 23

Python os.walk() method

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.

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

Upvotes: 1

Views: 447

Answers (1)

In Windows each process may set a current working directory on each drive separately. D: means the current working directory on drive D. Here the behaviour occurs, because on all other drives the current working directory is set to the root directory, but on D: it is the D:\Dir1\Dir2\Dir3\ because the working directory was changed to the location of the script. To refer to the root directory of D: unambiguously, you need to use D:\. Thus

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):            

Upvotes: 2

Related Questions