Change a drive letter


The requirement: Change the drive letter of an existing device

This problem came up on the python-win32 list when users were finding that USB key mappings were conflicting with logon-script network drive mappings. The working solution involved using the external diskpart.exe program to reassign a volume's letter. A not-too-different alternative is to use the mountvol command. WMI was suggested, but the solutions all rely on the relatively new methods in Win32_Volume, only available from win2k3 onwards. And, since I don't have access to any Win2k3 boxes I'm reluctant to post an untested solution. Finally, Roger Upole came to the rescue with a three-line script using functions already available in the win32file module.

Using diskpart.exe

Adapted from a solution by Mike Driscoll

import subprocess

diskpart_data = "change-drive.txt"
open (diskpart_data, "w").write ("""
select volume G: 
assign letter=T
""") ('diskpart /s %s' % diskpart_data) 

Using mountvol

(Not sure why I posted this, since it's both effectively identical to and more fragile than the win32file solution below. Perhaps just to show that mountvol existed, in case anyone wanted to know).

import subprocess

remap_from, remap_to = "g:\\", "t:\\"

mountvol = subprocess.Popen (["mountvol", remap_from, "/L"], stdout=subprocess.PIPE)
volume_name = mountvol.communicate ()[0].strip () (["mountvol", remap_from, "/D"]) (["mountvol", remap_to, volume_name])

Using win32file

Adapted from a solution by Roger Upole

import win32file

remap_from, remap_to = "g:\\", "t:\\"

volume_name = win32file.GetVolumeNameForVolumeMountPoint (remap_from)
win32file.DeleteVolumeMountPoint (remap_from)
win32file.SetVolumeMountPoint (remap_to, volume_name)