使用Python查找驱动器字母(Windows)

3

我希望编写一个Python脚本(我是新手),该脚本将搜索Windows上每个连接的驱动器的根目录以查找关键文件,并返回存放此文件的驱动器号码,然后将其设置为变量。

当前代码:

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'):

-- 然后对每个驱动器字母A到Z都重复执行。显然,这将需要输入大量内容,我只是想知道是否有一种解决方法可以保持我的代码整洁且尽可能简洁(或者这是唯一的方法吗?)。
此外,是否有一种方法可以在未找到驱动器时打印出错误(例如,请插入您的USB),然后返回到开始/循环?类似于:
print('Please plug in our USB drive')
return-to-start

这有点像GOTO命令提示符命令吗?

编辑:

对于未来有类似问题的人,这是解决方案:

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()

这个脚本会提示用户插入一个包含'file.id'的驱动器,当驱动器连接成功后,会将驱动器盘符打印到控制台,并且允许使用 'drive' 作为变量。

4个回答

11

Python有一个简单的解决方案,使用pathlib模块。

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

3

使用循环生成路径名:

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将此与thefourtheye的回复结合起来。我在这里遇到了一些错误,想知道您是否能提供一些帮助:http://stackoverflow.com/questions/29059399/searching-for-a-usb-in-python-is-returning-there-is-no-disk-in-drive - Julian White

3

由于您想要重复检查驱动器是否存在,因此您可能希望将其作为单独的函数移动,如下所示:

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 ""

如果您希望程序重复提示用户插入设备,则可以像这样在循环中运行:

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()

起初,我们会尝试使用 get_usb_drive() 获取驱动器,如果无法找到,则返回一个空字符串。然后我们会迭代直到从 get_usb_drive() 返回的值为空字符串,并提示用户插入设备并等待按键。 注意:我们使用os.path.join来创建实际的文件系统路径,而不是所有手动字符串连接。

1
这里有一个注释(https://dev59.com/UHRA5IYBdhLWcg3wyBH1#827398),指出类似的方法(`os.path.isdir` vs. os.path.exists)可能会弹出一个Windows对话框。我在我的桌面上没有这样的驱动器,所以我不能轻易地测试,但值得注意。如果它不会弹出对话框(或者您没有安装那种类型的驱动器),这种方法非常干净和直接。 - jedwards
@jedwards 是的,如果我使用.bat(使用if exist cmd)搜索驱动器号,我也会遇到类似的错误。我的电脑上有一个SD卡读卡器,它会弹出一个“错误”提示,因为它没有媒体 - 但是Python的os.path.exists似乎可以很好地处理这个问题。thefourtheye 我会尽快测试这个命令。谢谢。 - Julian White
请在您的问题中编辑并包含您尝试过的内容。 - thefourtheye
当is.path.exists返回true时,您应该返回。在我的例子中有两个返回语句。请检查。 - thefourtheye
我简直不敢相信我完全错过了那个!我的新手因素真的很明显。我将使用解决方案更新原始问题,以便有类似疑问的人知道解决方案。谢谢! - Julian White
显示剩余2条评论

0
最简单的方法是:
from pathlib import Path
root = Path(__file__).anchor  # 'C:\' or '\' on unix.

适用于所有系统。 那么你可以这样做:

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

在控制台中它无法工作,因为使用了文件路径。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接