tags:

views:

628

answers:

4

More or less what it says on the tin: is there an (easy) way in Python to list all the currently in-use drive letters in a windows system?

(My google-fu seems to have let me down on this one.)

Related:

+16  A: 
import win32api

drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]
print drives

Adapted from: http://www.faqts.com/knowledge_base/view.phtml/aid/4670

Ayman Hourieh
FANTASTIC. Worked perfect.
Electrons_Ahoy
I just tried it in 2.6, and got an extra empty string at the end. Still a good answer.
Mark Ransom
@Mark: edit to fix
Claudiu
Just to make sure you don't discard any non-empty strings, consider using `drives = [drivestr in drives.split('\000') if drivestr]`
Wesley
+15  A: 

Without using any external libraries, if that matters to you:

import string
from ctypes import windll

def get_drives():
    drives = []
    bitmask = windll.kernel32.GetLogicalDrives()
    for letter in string.uppercase:
        if bitmask & 1:
            drives.append(letter)
        bitmask >>= 1

    return drives

if __name__ == '__main__':
    print get_drives()     # On my PC, this prints ['A', 'C', 'D', 'F', 'H']
RichieHindle
Any reason not to use string.lowercase or string.ascii_lowercase instead of string.letters[len(string.letters)/2:] ?
John Fouhy
@John: No reason - thanks for the suggestion, now changed to string.uppercase (because for drive letters I prefer caps, don't know why 8-)
RichieHindle
[c+':\\' for c in string.lowercase if os.path.isdir(c+':\\')]
Berry Tsakala
Berry: that will pop up nasty Windows dialogs if you have removable media drives without media in them...
Ted Mielczarek
+2  A: 

Those look like better answers. Here's my hackish cruft

import os, re
re.findall(r"[A-Z]+:.*$",os.popen("mountvol /").read(),re.MULTILINE)
TokenMacGuy
+7  A: 

The Microsoft Script Repository includes this recipe which might help. I don't have a windows machine to test it, though, so I'm not sure if you want "Name", "System Name", "Volume Name", or maybe something else.

John Fouhy
Thank you for link to Microsoft Script Repository.
Konstantin
I've always felt that it is an excellent resource for Windows progarmmers that is not widely-enough known :-)
John Fouhy
Another +1 for the link to the Microsoft Script Repository, I'd never heard of it before.
Mark Ransom