Jul*_*ite 3 python string python-3.x
我正在尝试编写一个 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'):
Run Code Online (Sandbox Code Playgroud)
-- 然后对每个驱动器字母 A 到 Z 重复出现。自然,这会需要输入很多内容,我只是想知道是否有一种解决方法可以使我的代码保持整洁并尽可能少(或者这是唯一的方法? )。
此外,如果找不到驱动器(即请插入 USB),有没有办法让它打印错误,然后返回到开始/循环?就像是
print('Please plug in our USB drive')
return-to-start
Run Code Online (Sandbox Code Playgroud)
有点像 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()
Run Code Online (Sandbox Code Playgroud)
该脚本提示用户插入包含“file.id”的驱动器,连接后将驱动器号打印到控制台并允许使用“drive”作为变量。
r3t*_*t40 11
Python对此有一个简单的解决方案。使用pathlib模块。
import pathlib
drive = pathlib.Path.home().drive
print(drive)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18863 次 |
| 最近记录: |