i have some questions about the following code.
from win32 import win32file
drives = []
drivebits=win32file.GetLogicalDrives()
for d in range(1,26):
mask=1 << d
if drivebits & mask:
drname='%c:\\' % chr(ord('A')+d)
t=win32file.GetDriveType(drname)
if t == win32file.DRIVE_REMOVABLE:
drives.append(drname)
print(drives)
1-When you use the GetLogicalDrives from win32 module it returns an integer.Can someone explain why?
2-Why the loop's range is between 1 and 26?
3-Whats the reason of the bitwise AND?
Thank you
The win32
module is a really low-level wrapper around the Win32 API, so usually you can look at the Windows documentation of the function name and get the info you need. You can find the documentation for GetLogicalDrives here.
To answer your question:
The integer corresponds to the available drives: each available drive gets 1 bit. So if no drives are available, you'd get 0
, assuming a 32-bit integer) back. If every drive was available, you'd get 0b11111111111111111111111111
(in binary)
There are 26 letters, so it loops through 26 numbers. Actually, the code you posted is only looping from 1 to 25, and I think that is a bug. It should just be range(26)
.
The bitwise and is to check the individual bits of the returned integer. Remember, each bit of the integer corresponds to a drive letter. Let's say, for example, that your C, D, and G drives are available. You can visualize the returned value like this, where the first row is the potential drives, and the second row is the returned value in binary:
ZYXWVUTSRQPONMLKJIHGFEDCBA # drive the bit corresponds to
00000000000000000001001100 # returned value, in binary, if C, D, and G are available
To check if drive A is available, you need to check that the smallest bit is 1. The way to check individual bits is with a bitwise and. To do the check for the smallest bit, you would do drivebits & 1
, to check drive B, you need to check the second bit: drievebits & (1 << 1)
. To check C, you need the third bit: drivebits & (1 << 2)
. And so on.
Some example returns:
If you only have drive C available, GetLogicalDrives
would return 0b100
(binary), or 4
(decimal). If C and D were available, you'd get 0b1100
(binary), or 12
(decimal).