3

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.

Julian White
  • 1,603
  • 3
  • 12
  • 12

4 Answers4

11

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

import pathlib
drive = pathlib.Path.home().drive
print(drive)
r3t40
  • 579
  • 6
  • 12
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
Dan D.
  • 73,243
  • 15
  • 104
  • 123
  • Thanks @Dan D combined this with thefourtheye's reply. Getting errors here, wondering if you can offer some assistance: http://stackoverflow.com/questions/29059399/searching-for-a-usb-in-python-is-returning-there-is-no-disk-in-drive – Julian White Mar 15 '15 at 13:10
3

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.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 1
    There's a note [here](http://stackoverflow.com/a/827398/736937) that a similar approach (`os.path.isdir` vs. `os.path.exists`) can pop up a windows dialog. I don't have a drive like that on my desktop, so I can't easily test, but might be worth noting. If it doesn't (or you don't have that type of drive installed), this approach is very clean and straightforward. – jedwards Mar 13 '15 at 06:32
  • @jedwards yes I also get a similar error if I do this with a .bat (using if exist cmd) searching drive letters, I have an SD card reader on my computer and that spits out an 'error' as it has 'no media' - however Python's os.path.exists seems to handle that just fine. thefourtheye I will test this command asap. thanks – Julian White Mar 13 '15 at 09:45
  • OK couldn't get your code to work so I revised with also taking note to Dan D's: `from string import ascii_uppercase import os def get_usb_drive(): for drive in ascii_uppercase: if os.path.exists('%s:\\File.ID' % drive): drive='%s:\\' % drive print('USB mounted to', drive) return "" 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()` Issue now, it loops even if the drive letter is found. It's probably something simple, alas, I'm a noob – Julian White Mar 13 '15 at 10:25
  • Please edit and include what you tried in your question itself – thefourtheye Mar 13 '15 at 10:28
  • You should return when is.path.exists return true. In my example there are two return statements. Please check – thefourtheye Mar 13 '15 at 10:56
  • I can't believe I totally missed that! My newbie factor really shines there. I will update the original question with the solution so people who have a similar inquiry will know the solution. Thanks! – Julian White Mar 13 '15 at 11:01
  • @thefourtheye - Got it to work however getting some issues as jedwards pointed out - any insight? Asked in new thread here: http://stackoverflow.com/questions/29059399/searching-for-a-usb-in-python-is-returning-there-is-no-disk-in-drive – Julian White Mar 15 '15 at 13:18
0

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.

Zzoomrus
  • 19
  • 3