Listing files efficiently on win32 with ctypes
Though cPython provides access to these functions though ctypes, finding a good example is fairly difficult. Here is a short code snippet that works with Python 2:
import ctypes, ctypes.wintypes
FILE_ATTRIBUTE_DIRECTORY = 0x10
INVALID_HANDLE_VALUE = -1
BAN = (u'.', u'..')
FindFirstFile = ctypes.windll.kernel32.FindFirstFileW
FindNextFile = ctypes.windll.kernel32.FindNextFileW
FindClose = ctypes.windll.kernel32.FindClose
out = ctypes.wintypes.WIN32_FIND_DATAW()
fldr = FindFirstFile(u"C:\\Windows\\*", ctypes.byref(out))
if fldr == INVALID_HANDLE_VALUE:
raise ValueError("invalid handle!")
try:
while True:
if out.cFileName not in ban:
isdir = out.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
ts = out.ftLastWriteTime
timestamp = (ts.dwLowDateTime << 32) | ts.dwHighDateTime
print str(out.cFileName), isdir, timestamp
if not FindNextFile(fldr, ctypes.byref(out)):
break
finally:
FindClose(fldr)