簡體   English   中英

使用 Python 查找盤符 (Windows)

[英]Using Python to find drive letter (Windows)

我正在嘗試編寫一個 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”的驅動器,並在附加時將驅動器號打印到控制台並允許使用“驅動器”作為變量。

由於您想反復檢查驅動器是否存在,您可能希望將其作為單獨的函數移動,如下所示

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來創建實際的文件系統路徑,而不是所有手動字符串連接。

Python對此有一個簡單的解決方案。 使用 pathlib 模塊。

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

使用循環並生成路徑名:

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

最簡單的方法是:

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.

它在控制台中不起作用,因為使用文件路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM