【发布时间】:2022-04-20 19:37:26
【问题描述】:
我正在尝试编写一个 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 重复出现。当然,这将是很多需要输入的内容,我只是想知道是否有一种解决方法可以使我的代码保持整洁和尽可能少(或者这是唯一的方法?)。
此外,如果找不到驱动器(IE 说请插入您的 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”的驱动器,并在连接时将驱动器号打印到控制台并允许使用“驱动器”作为变量。
【问题讨论】:
标签: python string python-3.x