Skip to content

Instantly share code, notes, and snippets.

@Cologler
Created August 21, 2020 03:21
Show Gist options
  • Save Cologler/2f9c780ca71be7288b95c09e5ac539cd to your computer and use it in GitHub Desktop.
Save Cologler/2f9c780ca71be7288b95c09e5ac539cd to your computer and use it in GitHub Desktop.
get windows drive label
# -*- coding: utf-8 -*-
#
# Copyright (c) 2020~2999 - Cologler <[email protected]>
# ----------
#
# ----------
from ctypes import windll, create_unicode_buffer, c_wchar_p, sizeof
from string import ascii_uppercase
def get_drive_labels() -> dict:
'''
get a drive label mapping like `{'C:': 'System'}`
'''
# from https://stackoverflow.com/questions/827371
rv = {}
volumeNameBuffer = create_unicode_buffer(1024)
fileSystemNameBuffer = create_unicode_buffer(1024)
serial_number = None
max_component_length = None
file_system_flags = None
drive_names = []
# Get the drive letters, then use the letters to get the drive names
bitmask = (bin(windll.kernel32.GetLogicalDrives())[2:])[::-1] # strip off leading 0b and reverse
drive_letters = [ascii_uppercase[i] + ':/' for i, v in enumerate(bitmask) if v == '1']
for d in drive_letters:
rc = windll.kernel32.GetVolumeInformationW(c_wchar_p(d), volumeNameBuffer, sizeof(volumeNameBuffer),
serial_number, max_component_length, file_system_flags,
fileSystemNameBuffer, sizeof(fileSystemNameBuffer))
if rc:
rv[d[:2]] = volumeNameBuffer.value
return rv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment