Reputation: 23
How can I find out the drive letters of available CD/DVD drives?
I am using Python 2.5.4 on Windows.
Upvotes: 2
Views: 4575
Reputation: 88747
Using win32api you can get list of drives and using GetDriveType you can check what type of drive it is, you can access win32api either by 'Python for Windows Extensions' or ctypes module
Here is an example using ctypes:
import string
from ctypes import windll
driveTypes = ['DRIVE_UNKNOWN', 'DRIVE_NO_ROOT_DIR', 'DRIVE_REMOVABLE', 'DRIVE_FIXED', 'DRIVE_REMOTE', 'DRIVE_CDROM', 'DRIVE_RAMDISK']
def get_drives():
drives = []
bitmask = windll.kernel32.GetLogicalDrives()
for letter in string.uppercase:
if bitmask & 1:
drives.append(letter)
bitmask >>= 1
return drives
for drive in get_drives():
if not drive: continue
print "Drive:", drive
try:
typeIndex = windll.kernel32.GetDriveTypeW(u"%s:\\"%drive)
print "Type:",driveTypes[typeIndex]
except Exception,e:
print "error:",e
This outputs:
Drive: C
Type: DRIVE_FIXED
Drive: D
Type: DRIVE_FIXED
Drive: E
Type: DRIVE_CDROM
Upvotes: 10
Reputation: 193696
If you use the WMI Module, it's very easy:
import wmi
c = wmi.WMI()
for cdrom in c.Win32_CDROMDrive():
print cdrom.Drive, cdrom.MediaLoaded
The Drive
attribute will give you the drive letter and MediaLoaded
will tell you if there's something in the drive.
In case you didn't know, WMI standards for Windows Management Instrumentation and is an API that allows you to query management information about a system. (For what it's worth, WMI is the Windows implementation of the Common Information Model standard.) The Python WMI Module gives you easy access to the Windows WMI calls.
In the code above we query the Win32_CDROMDrive
WMI Class to find out about the CD ROM drives on the system. This gives us a list of objects with a huge number of attributes which tells us everything we could ever want to know about the CD Drives. We check the drive letter and media state, since that's all we care about right now.
Upvotes: 2
Reputation: 54302
Use GetDriveType Function from win32file
module.
Sample code:
import win32file
for d in ('C', 'D', 'E', 'F', 'G'):
dname='%c:\\' % (d)
dt=win32file.GetDriveType(dname)
if dt == win32file.DRIVE_CDROM:
print('%s is CD ROM' % (dname))
Upvotes: 2
Reputation: 110108
With the Python for Windows extensions, you can use:
[drive for drive in win32api.GetLogicalDriveStrings().split('\x00')[:-1]
if win32file.GetDriveType(drive)==win32file.DRIVE_CDROM]
Adapted from this post.
This will give you the drive letters even if there is no CD/DVD in the drive.
Upvotes: 2