如何在Python中获取驱动器的名称

9

我有一个有效驱动器字母列表,并且我想向最终用户提供选择。我希望向他们显示驱动器的名称。以下是应该显示驱动器名称F:\的代码:

import ctypes

kernel32 = ctypes.windll.kernel32
buf = ctypes.create_unicode_buffer(1024)

kernel32.GetVolumeNameForVolumeMountPointW(
    ctypes.c_wchar_p("F:\\"),
    buf,
    ctypes.sizeof(buf)
)

print buf.value

然而,这个输出结果是\\?\Volume{a8b6b3df-1a63-11e1-9f6f-0007e9ebdfbf}\。我该如何获取Windows资源管理器中显示的字符串(例如,我拥有的某个闪存驱动器的KINGSTON)?


编辑:

仍然不起作用:

volumeNameBuffer = ctypes.create_unicode_buffer(1024)
fileSystemNameBuffer = ctypes.create_unicode_buffer(1024)

kernel32.GetVolumeInformationW(
    ctypes.c_wchar_p("C:\\"),
    volumeNameBuffer,
    ctypes.sizeof(volumeNameBuffer),
    fileSystemNameBuffer,
    ctypes.sizeof(fileSystemNameBuffer)
)

这给我带来了这个错误:
WindowsError: exception: access violation reading 0x3A353FA0
7个回答

17
为什么不使用pywin32模块中的win32api.GetVolumeInformation呢?
import win32api
win32api.GetVolumeInformation("C:\\")

输出
('WINDOWS', 1992293715, 255, 65470719, 'NTFS')

8
使用上述片段,我填写了缺失的(可选的、空的)参数作为快速帮助程序:
import ctypes
kernel32 = ctypes.windll.kernel32
volumeNameBuffer = ctypes.create_unicode_buffer(1024)
fileSystemNameBuffer = ctypes.create_unicode_buffer(1024)
serial_number = None
max_component_length = None
file_system_flags = None

rc = kernel32.GetVolumeInformationW(
    ctypes.c_wchar_p("F:\\"),
    volumeNameBuffer,
    ctypes.sizeof(volumeNameBuffer),
    serial_number,
    max_component_length,
    file_system_flags,
    fileSystemNameBuffer,
    ctypes.sizeof(fileSystemNameBuffer)
)

print volumeNameBuffer.value
print fileSystemNameBuffer.value

这应该可以复制粘贴。


7

1
你还没有传递另外三个参数:lpVolumeSerialNumberlpMaximumComponentLengthlpFileSystemFlags。文档中的“可选”标识并不意味着你可以简单地省略它们,而是表示如果你对该值不感兴趣,可以将NULL作为指向该信息的指针传递。 - Greg Hewgill
@GregHewgill:太棒了。谢谢! - Eric

2
你可以执行Windows shell命令并解析输出。
在Python 3.x中:
import subprocess 
def getDriveName(driveletter):
    return subprocess.check_output(["cmd","/c vol "+driveletter]).decode().split("\r\n")[0].split(" ").pop()

print (getDriveName("d:"))

在Python 2.7中:

import subprocess 
def getDriveName(driveletter):
    return subprocess.check_output(["cmd","/c vol "+driveletter]).split("\r\n")[0].split(" ").pop()

print getDriveName("d:")

1
import win32api
import win32file
drives = win32api.GetLogicalDriveStrings()
drives =  drives.split('\000')[:-1]

for drive in drives:
    if win32file.GetDriveType(drive)==win32file.DRIVE_REMOVABLE:
        label,fs,serial,c,d = win32api.GetVolumeInformation(drive)
        print(label)

2
你的答案可以通过提供更多支持信息来改进。请[编辑]以添加更多细节,例如引用或文档,以便他人可以确认您的答案是否正确。您可以在帮助中心中找到有关撰写良好答案的更多信息。 - Community
你能使用反引号格式化代码,使其更易读吗? - Keith E. Truesdell

1
  • 根据给定的驱动器标签返回驱动器字母
  • 如果未找到驱动器标签,则返回“notfound”

def findDriveByDriveLabel(driveLabel):

drvArr = ['c:', 'd:', 'e:', 'f:', 'g:', 'h:', 'i:', 'j:', 'k:', 'l:']
for dl in drvArr:
    try:
        if (os.path.isdir(dl) != 0):
            val = subprocess.check_output(["cmd", "/c vol " + dl])
            if (driveLabel in str(val)):
                return dl + "/"
    except:
        print("Error: findDriveByDriveLabel(): exception")

return "notfound"

-1
您可以使用以下代码获取驱动器名称,如果您发现有用的话。
import win32api
import win32con
import win32file

def get_removable_drives():
    drives = [i for i in win32api.GetLogicalDriveStrings().split('\x00') if i]
    #print(drives)
    rdrives = [d for d in drives if win32file.GetDriveType(d) == win32con.DRIVE_REMOVABLE]
    return rdrives

drive_list = get_removable_drives()

for i in drive_list:
    print(win32api.GetVolumeInformation(i)[0]+'('+i+')')


1
从 https://dev59.com/953ha4cB1Zd3GeqPbONh#58645744 复制的程序相关内容。-1. - CristiFati

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接