How to Map Network Drive Paths to Local Paths in Python

Convert mock SMB network drive paths (like 'S:\reports\q1.xlsx') to local placeholder paths and back using a simple mapping dictionary in Python.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 15 views 0 copies

Python code

42 lines
Python 3.9+
"""Map mock SMB network drive paths to local placeholder paths."""
from dataclasses import dataclass

@dataclass(frozen=True)
class NetworkDrive:
    letter: str
    remote_path: str

DRIVES = {
    "S:": NetworkDrive("S", r"\\server01\shares\sales"),
    "M:": NetworkDrive("M", r"\\server02\media\movies"),
    "X:": NetworkDrive("X", r"\\nas\public\documents"),
}

LOCAL_BASE = {"S": "/mnt/sales", "M": "/mnt/media", "X": "/mnt/docs"}

def smb_to_local(smb_path: str, drives: dict = DRIVES) -> str:
    """Convert a mock SMB path (e.g. 'S:\\reports\\q1.xlsx') to a local path."""
    if not smb_path or smb_path[0] not in drives:
        raise ValueError(f"Drive letter not mapped: {smb_path}")
    letter = smb_path[0]
    rest = smb_path[2:].replace("\\", "/")
    return f"{LOCAL_BASE[letter]}/{rest}".rstrip("/")

def local_to_smb(local_path: str) -> str:
    """Convert a mock local path back to an SMB path."""
    for letter, base in LOCAL_BASE.items():
        if local_path.startswith(base + "/") or local_path == base:
            suffix = local_path[len(base):].replace("/", "\\")
            return drives[letter + ":"].remote_path + suffix
    raise ValueError(f"No matching drive for path: {local_path}")

if __name__ == "__main__":
    test_paths = [
        "S:\\reports\\q1.xlsx",
        "M:\\movies\\inception\\movie.mp4",
        "S:",
    ]
    for p in test_paths:
        local = smb_to_local(p)
        back = local_to_smb(local)
        print(f"{p!r} -> {local!r} -> {back!r}")

Output

stdout
'S:\\reports\\q1.xlsx' -> '/mnt/sales/reports/q1.xlsx' -> 'S:\\reports\\q1.xlsx'
'M:\\movies\\inception\\movie.mp4' -> '/mnt/media/movies/inception/movie.mp4' -> 'M:\\movies\\inception\\movie.mp4'
'S:' -> '/mnt/sales' -> 'S:'

How it works

The smb_to_local function extracts the drive letter from the SMB path, replaces backslashes with forward slashes, and prepends the local base path. The local_to_smb function iterates through the local base paths to find a match, then converts forward slashes back to backslashes and prepends the remote SMB path. Using a dataclass for NetworkDrive keeps the drive metadata clean and immutable. The LOCAL_BASE dictionary acts as a simple lookup table for mapping drive letters to local mount points. The @dataclass(frozen=True) decorator ensures drive objects are hashable and immutable, making them safe to use as dictionary keys.

Common mistakes

  • Forgetting to handle the double backslash in network paths (use raw strings like r'\\server01\shares')
  • Not stripping trailing slashes when converting to local paths, which can break path joins
  • Assuming all network paths use backslashes — some tools output forward slashes depending on the OS
  • Ignoring edge cases like just the drive letter ('S:') without a subpath

Variations

  1. Use environment variables or a config file to store the drive mappings instead of hardcoding them
  2. Use `pathlib.PurePath` for more robust cross-platform path manipulation

Real-world use cases

  • Building cross-platform automation scripts that need to reference network-shared files with local equivalents
  • Creating a mock file system for testing code that depends on SMB paths without access to a real network
  • Writing a migration tool that rewrites hardcoded network paths in configuration files to local paths

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.