Eric Bergman-Terrell's Blog

Python Programming Tip: Map Windows Volume Label to Corresponding Drive Letter
February 6, 2021

I've written a file sync and verify program in Python. I use it to sync important files to backup drives, which are external USB drives. I've noticed that the drive letters assigned to such drives can sometimes change without warning.

For this reason, I prefer to specify a unique volume label for a USB drive, and have my app determine convert the volume label to the corresponding drive letter at run-time. For instance, my "Backup" drive currently has a drive letter of "E":

Volume Label

To convert the volume label to the current drive letter, I call FileSystemUtils.label_to_drive_letter. For example:

FileSystemUtils.label_to_drive_letter('Backup')

Source Code:

import os
import win32file
import win32api
import win32con
import pywintypes
import shutil
import platform
from tenacity import *
from StringLiterals import StringLiterals
from AppException import AppException
from Constants import Constants
from Globals import app_globals

...

class FileSystemUtils:
    ...
    @staticmethod
    def label_to_drive_letter(volume_label):
        for letter in FileSystemUtils._char_range('A', 'Z'):
            try:
                volume_info = win32api.GetVolumeInformation(f'{letter}:\\')

                if volume_info[0] == volume_label:
                    return letter

            except pywintypes.error:
                pass

        raise AppException(f'Cannot map volume label "{volume_label}" to drive letter')

    @staticmethod
    def _char_range(c1, c2):
        # https://stackoverflow.com/questions/7001144/range-over-character-in-python
        """Generates the characters from `c1` to `c2`, inclusive."""
        """Using range instead of xrange as xrange is deprecated in Python3"""
        for c in range(ord(c1), ord(c2) + 1):
            yield chr(c)

The above source code is based on ideas from another developer. See the link in the comment.

Complete source code available here.

My mood is subject to change
My mood is subject to change without notice!

Keywords: Python, Python 3, Windows, volume label, drive letter

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021
Vault (Desktop) Version 0.72 ReleasedOctober 6, 2021
EBT Compass is Now Available for Android DevicesJune 2, 2021