我希望编写一个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' 作为变量。