Windows 10下用Python获取本地驱动器、网络驱动器及网络位置列表
在Windows 10用Python获取本地/网络驱动器及网络位置的完整列表
我来帮你解决这个问题!之前靠解析快捷方式的方案确实不够可靠——快捷方式可能被移动、重命名甚至删除,很容易导致获取的信息不全或出错。下面给你几个直接调用Windows系统API的更优方案,能稳定获取本地驱动器、映射网络驱动器和网络位置的完整列表:
方案1:使用pywin32调用Win32 API(最精准)
这个方案分两步走:先获取本地和映射网络驱动器,再单独提取「此电脑」中的非映射网络位置。
步骤1:获取本地与映射网络驱动器
import win32api def get_local_and_mapped_drives(): drive_list = [] # 获取系统所有逻辑驱动器字符串,分割后过滤空值 drives = win32api.GetLogicalDriveStrings().split('\000')[:-1] for drive in drives: # 判断驱动器类型:3=本地磁盘,4=网络映射驱动器 drive_type = win32api.GetDriveType(drive) if drive_type in (3, 4): drive_list.append(drive) return drive_list # 调用示例 local_mapped_drives = get_local_and_mapped_drives() print(local_mapped_drives) # 输出类似 ["C:\\", "D:\\", "Z:\\"]
步骤2:获取「此电脑」中的网络位置
这部分需要通过Windows Shell对象访问系统注册的网络共享位置:
import win32com.client def get_network_locations(): network_locations = [] shell = win32com.client.Dispatch("Shell.Application") # 命名空间4对应「此电脑」文件夹 computer_folder = shell.Namespace(4) for item in computer_folder.Items(): # 筛选出路径以\\开头的网络文件夹 if item.IsFolder and item.Path.startswith('\\\\'): network_locations.append(item.Path) return network_locations # 调用示例 network_locations = get_network_locations() print(network_locations) # 输出类似 ["\\\\some.network.address\\some_folder"]
合并完整列表
把两部分结果合并,就得到你需要的完整列表了:
full_list = get_local_and_mapped_drives() + get_network_locations() print(full_list) # 最终输出符合期望:["C:\\", "D:\\", "\\\\some.network.address\\some_folder"]
方案2:使用psutil库(更简洁)
psutil是跨平台的系统监控库,在Windows上也能轻松获取磁盘信息,结合上面的网络位置获取函数就能快速得到结果:
import psutil def get_drives_with_psutil(): drive_list = [] # 获取所有磁盘分区(all=True参数包含网络驱动器) partitions = psutil.disk_partitions(all=True) for part in partitions: # 筛选本地磁盘(NTFS/FAT32等格式)和网络驱动器 if part.fstype in ('NTFS', 'FAT32', 'NETWORK'): drive_list.append(part.mountpoint) return drive_list # 合并结果 full_list = get_drives_with_psutil() + get_network_locations() print(full_list)
为什么这些方案更优?
- 稳定性高:直接调用Windows系统原生API,完全不受快捷方式的状态影响;
- 准确性强:能精准识别系统认可的所有驱动器和网络位置,不会遗漏或误判;
- 可维护性好:代码逻辑清晰,后续扩展或调整需求更方便。
内容的提问来源于stack exchange,提问作者clfaster
相关产品推荐
相关产品推荐

