Python 2: Get network share path from drive letter

烈酒焚心 提交于 2019-12-01 16:16:34

Use win32wnet from pywin32 to convert your drive letters. For example:

import win32wnet
import sys

print(win32wnet.WNetGetUniversalName(sys.argv[1], 1))

This gives me something like this when I run it:

C:\test>python get_unc.py i:\some\path
\\machine\test_share\some\path

Using ctypes and the code shown in the first answer in this post: Get full computer name from a network drive letter in python, it is possible to get the drive paths for every network drive, or a selected few.

The get_connection function given will throw an error if the drive is not a network drive, either local or removable drives, this can be accounted for with

# your drive list
available_drives = ['%s:' % d for d in string.ascii_uppercase if os.path.exists('%s:' % d)]
for drive in available_drives:
    try:
        # function from linked post
        print(get_connection(drive))
    except WindowsError: # thrown from local drives
        print('{} is a local drive'.format(drive))

Here's how to do it in python ≥ 3.4, with no dependencies!*

from pathlib import Path

def unc_drive(file_path):
    return str(Path(file_path).resolve())

*Note: I just found a situation in which this method fails. One of my company's network shares has permissions setup such that this method raises a PermissionError. In this case, win32wnet.WNetGetUniversalName is a suitable fallback.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!