How would I check if a raw(Windows) drive exists in python? i.e. "\\.\PhysicalDriveN" where N in the disk number
Right now I can check if a raw drive exists(as admin) by opening and immediately closing it. If there is an exception, then the raw device may not exist, otherwise it does. I know that's not very pythonic. Is there a better way?
os.access(drive_name, os.F_OK) always returns False. Same with with os.path.exists(drive_name). I'd prefer just to use the python standard library. os.stat(drive_name) cannot find the device either.
Example of my working code:
drive_name = r"\\.\PhysicalDrive1"
try:
open(drive_name).close()
except FileNotFoundError:
print("The device does not exist")
else:
print("The device exists")
As eryksun pointed out in the comments,
ctypes.windll.kernel32.QueryDosDeviceWcan be used to test for whether the device symbolic link exists(PhysicalDrive1is a symbolic link to the actual device location). Thectypesmodule allows one to access this API function, through a Dynamically-linked library.QueryDosDeviceWrequires the drive name as a string, a character array, and the character array's length. The character array stores the raw device that the drive name maps to. The function returns the amount of characters stored in the character array, which would be zero if the drive doesn't exist.The
targetcharacter array object might have the value"\Device\Harddisk2\DR10"stored in itNote In python 3 strings are unicode by default, which is why
QueryDosDeviceW(above) works. For Python 2,ctypes.windll.kernel32.QueryDosDeviceAwould work in place ofQueryDocDeviceWfor byte strings.