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:


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:
    def label_to_drive_letter(volume_label):
        for letter in FileSystemUtils._char_range('A', 'Z'):
                volume_info = win32api.GetVolumeInformation(f'{letter}:\\')

                if volume_info[0] == volume_label:
                    return letter

            except pywintypes.error:

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

    def _char_range(c1, c2):
        """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

Vault 3 Source Code in GitHubMarch 3, 2021
Vault 3 (Desktop) Version 0.70 ReleasedFebruary 27, 2021
Vault 3 (Desktop) Version 0.68 ReleasedFebruary 17, 2021
Python Programming Tip: Generate Hash for a FileFebruary 14, 2021
Python Programming Tip: Implement Retries with EaseFebruary 6, 2021
Python Programming Tip: Map Windows Volume Label to Corresponding Drive LetterFebruary 6, 2021
Python Programming Tip: Prevent Sleep when Running on WindowsFebruary 6, 2021