Using Python to find drive letter (Windows)

Question:

I’m trying to write a python script (I’m a newbie) that will search the root directory of each connected drive on Windows for a key file and then return the drive letter it’s on setting a variable as the drive letter.

Currently I have:

import os
if os.path.exists('A:\File.ID'):
        USBPATH='A:\'
        print('USB mounted to', USBPATH)
    if os.path.exists('B:\File.ID'):
        USBPATH='B:\'
        print('USB mounted to', USBPATH)
    if os.path.exists('C:\File.ID'):

— And then recurring for every drive letter A through Z. Naturally this will be a lot to type out and I’m just wondering if there’s a workaround to keep my code tidy and as minimal as possible (or is this the only way?).

Additionally, is there a way to have it print an error if the drive isn’t found (IE say please plug in your USB) and then return to the start/loop? Something like

print('Please plug in our USB drive')
return-to-start

Kind of like a GOTO command-prompt command?

EDIT:

For people with similar future inquiries, here’s the solution:

from string import ascii_uppercase
import os


def FETCH_USBPATH():
    for USBPATH in ascii_uppercase:
         if os.path.exists('%s:\File.ID' % SVPATH):
            USBPATH='%s:\' % USBPATH
            print('USB mounted to', USBPATH)
            return USBPATH + ""
    return ""

drive = FETCH_USBPATH()
while drive == "":
    print('Please plug in USB drive and press any key to continue...', end="")
    input()
    drive = FETCH_USBPATH()

This script prompts the user to plug in a drive containing ‘file.id’ and when attached, prints the drive letter to console and allows the use of ‘drive’ as a variable.

Asked By: Julian White

||

Answers:

Use a loop and generate the path names:

import os
import string

for l in string.ascii_uppercase:
    if os.path.exists('%s:\File.ID' % l):
        USBPATH='%s:\' % l
        print('USB mounted to', USBPATH)
        break
Answered By: Dan D.

Since you want to repeatedly check if the drive exists, you may want to move that as a separate function, like this

from string import ascii_uppercase
from os import path


def get_usb_drive():
    for drive in ascii_uppercase:
        if path.exists(path.join(drive, "File.ID")):
            return drive + ":\"
    return ""

and then, if you want the program to repeatedly prompt the user to plugin the device, you might want to run it in a loop, like this

drive = get_usb_drive()
while drive == "":
    print('Please plug in our USB drive and press any key to continue...',end="")
    input()
    drive = get_usb_drive()

Initially, we ll try to get the drive with get_usb_drive() and if it fails to find one, it will return an empty string. And we iterate till the returned value from get_usb_drive() is an empty string and prompt the user to plugin the device and wait for the key press.

Note: We use os.path.join to create the actual file system paths, instead of all the manual string concatenation.

Answered By: thefourtheye

Python has a simple solution to this. Use the pathlib module.

import pathlib
drive = pathlib.Path.home().drive
print(drive)
Answered By: r3t40

Most easy way is:

from pathlib import Path
root = Path(__file__).anchor  # 'C:' or '' on unix.

Work for all systems.
Then you can do this:

some_path = Path(root).joinpath('foo', 'bar')  # C:foobar or foobar on unix.

It won’t work in console, because uses file path.

Answered By: Zzoomrus
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.