有没有办法列出python中所有可用的驱动器号?

Ele*_*hoy 43 python windows

或多或少在它上面说的:在Python中有一种(简单的)方法列出Windows系统中当前正在使用的所有驱动器号吗?

(我的google-fu似乎让我失望了.)

有关:

Ric*_*dle 61

不使用任何外部库,如果这对您很重要:

import string
from ctypes import windll

def get_drives():
    drives = []
    bitmask = windll.kernel32.GetLogicalDrives()
    for letter in string.uppercase:
        if bitmask & 1:
            drives.append(letter)
        bitmask >>= 1

    return drives

if __name__ == '__main__':
    print get_drives()     # On my PC, this prints ['A', 'C', 'D', 'F', 'H']
Run Code Online (Sandbox Code Playgroud)

  • Berry:如果你有可移动的媒体驱动器没有媒体,那将会弹出令人讨厌的Windows对话框...... (3认同)

Aym*_*ieh 58

import win32api

drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]
print drives
Run Code Online (Sandbox Code Playgroud)

改编自:http: //www.faqts.com/knowledge_base/view.phtml/aid/4670

  • 为了确保不丢弃任何非空字符串,请考虑使用`drives = [drivestr在drives.split('\ 000')中如果drivestr]` (2认同)

Sin*_*ion 10

那些看起来更好的答案.这是我的hackish cruft

import os, re
re.findall(r"[A-Z]+:.*$",os.popen("mountvol /").read(),re.MULTILINE)
Run Code Online (Sandbox Code Playgroud)

RichieHindle的回答中略微说道 ; 它并不是真的更好,但你可以让窗户做出实际的字母表字母

>>> import ctypes
>>> buff_size = ctypes.windll.kernel32.GetLogicalDriveStringsW(0,None)
>>> buff = ctypes.create_string_buffer(buff_size*2)
>>> ctypes.windll.kernel32.GetLogicalDriveStringsW(buff_size,buff)
8
>>> filter(None, buff.raw.decode('utf-16-le').split(u'\0'))
[u'C:\\', u'D:\\']
Run Code Online (Sandbox Code Playgroud)


Seb*_*sch 9

我写了这段代码:

import os
drives = [ chr(x) + ":" for x in range(65,91) if os.path.exists(chr(x) + ":") ]
Run Code Online (Sandbox Code Playgroud)

它基于@Barmaley 的回答,但具有不使用该string 模块的优点,以防您不想使用它。与@SingleNegationElimination 的回答不同,它也适用于我的系统。

  • ASCII 代码 65 至 90 对应于字母 AZ。该脚本检查所有可能的驱动器名称(从 A: 到 Z:),如果存在,则将它们添加到列表中。 (2认同)

Joh*_*uhy 8

微软脚本存储库包含这个配方可能有助于.我没有Windows机器来测试它,所以我不确定你是否想要"名称","系统名称","卷名"或其他东西.

  • 感谢您链接到Microsoft Script Repository. (2认同)
  • 我一直觉得它是 Windows 程序员的一个很好的资源,但并不广为人知:-) (2认同)
  • Microsoft Script Repository 链接的另一个 +1,我以前从未听说过。 (2认同)

Bar*_*ley 8

在Google上找到此解决方案,稍微修改一下.看似漂亮的pythonic,不需要任何"异国情调"的进口

import os, string
available_drives = ['%s:' % d for d in string.ascii_uppercase if os.path.exists('%s:' % d)]
Run Code Online (Sandbox Code Playgroud)


Pyt*_*Man 7

如果您只想列出磁盘上的驱动器而不是映射的网络驱动器,这是另一个很好的解决方案。如果您想按不同的属性过滤,只需打印 drps。

import psutil
drps = psutil.disk_partitions()
drives = [dp.device for dp in drps if dp.fstype == 'NTFS']
Run Code Online (Sandbox Code Playgroud)