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

9 投票
6 回答
20409 浏览
提问于 2025-04-17 07:21

我有一个有效的驱动器字母列表,想给用户提供一个选择,让他们看到驱动器的名称。下面这段代码应该能让我看到驱动器 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

6 个回答

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

这个应该可以直接复制粘贴使用。

17

你为什么不使用来自 pywin32模块win32api.GetVolumeInformation 呢?

import win32api
win32api.GetVolumeInformation("C:\\")

输出结果

('WINDOWS', 1992293715, 255, 65470719, 'NTFS')
7

试试这个 GetVolumeInformation 函数吧。它可以直接返回磁盘的卷标。

撰写回答