Welcome, guest | Sign In | My Account | Store | Cart

This is a quick-and-dirty Python script to detect the currently available drives on your Windows PC.

Python, 31 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from __future__ import print_function

'''
Author: Vasudev Ram
Copyright 2016 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: http://jugad2.blogspot.com
'''

from os.path import exists

def drives():
    # Limit of 'N' chosen arbitrarily.
    # For letters in the first half of the alphabet:
    for drive in range(ord('A'), ord('N')):
        print('Drive', chr(drive), 'exists:', exists(chr(drive) + ':'))

print()

drives()

print()

def drives2():
    drive_list = []
    for drive in range(ord('A'), ord('N')):
        if exists(chr(drive) + ':'):
            drive_list.append(chr(drive))
    return drive_list

print("The following drives exist:", drives2())

This Python drive detector utility makes use of the os.path module's exists() function, and in particular uses the fact that in Windows, a drive specification like "C:" is also considered to refer to the current directory on drive C. So the exists() function can check if that path (e.g. "C:") exists, and in doing so, it also happens to tell us if that drive C exists. This is why the script works, even though it does not call any OS API to return the list of drives.

If using on a system where a CD had been inserted into a CD drive recently, and was removed before the script was run, you may get a popup dialog from Windows, saying something to that effect. Choose an appropriate button in the dialog, to ignore that drive and continue checking for other drives.

The script has two functions, drives() and drives2(). drives() prints the lists of drives it finds. drives2() returns the list of drives it finds, so is more suitable for calling from another Python file, after doing "from drives import drives2".

More information and sample output here:

http://jugad2.blogspot.in/2016/09/quick-and-dirty-drive-detector-in.html