Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2: Get network share path from drive letter

If I use the following to get the list of all connected drives:

available_drives = ['%s:' % d for d in string.ascii_uppercase if os.path.exists('%s:' % d)]

How do I get the UNC path of the connected drives?

os.path just returns z:\ instead of \share\that\was\mapped\to\z

like image 940
Robben_Ford_Fan_boy Avatar asked Jul 07 '17 12:07

Robben_Ford_Fan_boy


People also ask

How do I find the path of a network shared file?

Via File Explorer To check the path of a network drive using File Explorer, click on 'This PC' on the left panel in Explorer. Then double-click the mapped drive under 'Network Locations'. The path of the mapped network drive can be seen at the top.

How do I find the path of a network drive in command prompt?

In Windows, if you have mapped network drives and you don't know the UNC path for them, you can start a command prompt (Start → Run → cmd.exe) and use the net use command to list your mapped drives and their UNC paths: C:\>net use New connections will be remembered.

How do I copy a mapped drive path?

Here's how. Find the file or folder whose path you'd like to copy in File Explorer. Hold down Shift on your keyboard and right-click on it. In the context menu that pops up, select “Copy As Path.”


2 Answers

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.

like image 149
Terry Davis Avatar answered Oct 01 '22 11:10

Terry Davis


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
like image 20
Peter Brittain Avatar answered Oct 01 '22 09:10

Peter Brittain