Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how do I check if a drive exists w/o throwing an error for removable drives?

Here's what I have so far:

import os.path as op
for d in map(chr, range(98, 123)): #drives b-z
    if not op.isdir(d + ':/'): continue

The problem is that it pops up a "No Disk" error box in Windows:

maya.exe - No Disk: There is no disk in the drive. Please insert a disk into drive \Device\Harddisk1\DR1 [Cancel, Try Again, Continue]

I can't catch the exception because it doesn't actually throw a Python error.

Apparently, this only happens on removable drives where there is a letter assigned, but no drive inserted.

Is there a way to get around this issue without specifically telling the script which drives to skip?

In my scenario, I'm at the school labs where the drive letters change depending on which lab computer I'm at. Also, I have zero security privileges to access disk management.

like image 838
jedmao Avatar asked Nov 15 '10 20:11

jedmao


2 Answers

import os 
def IsDriveExists(drive):
    return os.path.exists(drive + ':\\')
    
print(IsDriveExists('c')) 
print(IsDriveExists('d'))
print(IsDriveExists('e'))
print(IsDriveExists('x'))
print(IsDriveExists('v'))

this works in any os

like image 77
The EasyLearn Academy Avatar answered Oct 03 '22 23:10

The EasyLearn Academy


import os

possible_drives_list = [chr(97 + num).upper() for num in range(26)]

for drive in possible_drives_list:
    print(drive + ' exists :' + str(os.path.exists(drive + ':\\')))
like image 44
Hans Geukens Avatar answered Oct 03 '22 22:10

Hans Geukens