You are at a disadvantage.
Windows Explorer almost certainly uses FindFirstFile / FindNextFile to bypass the directory structure and collect size information (via lpFindFileData ) in a single pass, which essentially makes one system call for each file.
In this case, Python is unfortunately not your friend. In this way,
os.walk first calls os.listdir (which internally calls FindFirstFile / FindNextFile )- any additional system calls made from this point on may make you slower than Windows Explorer
os.walk then calls isdir for each file returned by os.listdir (which internally calls GetFileAttributesEx - or, before Win2k, a GetFileAttributes + FindFirstFile combo) to override whether to repeat or notos.walk and os.listdir will perform additional memory allocation , operations with strings and arrays, etc., to fill their return value- you then call
getsize for each file returned by os.walk (which again calls GetFileAttributesEx )
This is 3 times more system calls per file than Windows Explorer, plus memory allocation and overhead.
You can either use the Anurag solution, or try to call FindFirstFile / FindNextFile directly and recursively (which should be comparable to the performance of cygwin or another du32-port du -s some_directory .)
Refer to os.py for the implementation of os.walk , posixmodule.c for the implementation of listdir and win32_stat (both isdir and getsize .)
Note that Python os.walk is suboptimal on all platforms (Windows and * nices), up to Python3.1. For both Windows and * nices os.walk you can get around in one pass without calling isdir , because both FindFirst / FindNext (Windows) and opendir / readdir (* nix) already return the file type via lpFindFileData->dwFileAttributes (Windows) and dirent::d_type (* nix).
Perhaps intuitively, in most modern configurations (for example, Win7 and NTFS, and even some SMB implementations) GetFileAttributesEx twice as slow as FindFirstFile single file (possibly even slower than iterating over a directory with FindNextFile .)
Update: Python 3.5 includes the new PEP 471 os.scandir() , which solves this problem by returning the file attributes along with the file name. This new feature is used to speed up the built-in os.walk() (for both Windows and Linux). You can use the scandir module on PyPI to get this behavior for older versions of Python, including 2.x.
vladr Mar 21 2018-10-10T00: 00Z
source share