'Using Python to find drive letter (Windows)

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.



Solution 1:[1]

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.

Solution 2:[2]

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

import pathlib
drive = pathlib.Path.home().drive
print(drive)

Solution 3:[3]

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

Solution 4:[4]

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:\foo\bar or \foo\bar on unix.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 thefourtheye
Solution 2
Solution 3 Dan D.
Solution 4