Skip to main content

pathlib.PureWindowsPath - Pure Windows Path Operations

Class: pathlib.PureWindowsPath
Inheritance: PurePathPureWindowsPath
Category: File System Operations
Python Version: 3.4+

Overview

pathlib.PureWindowsPath is a subclass of PurePath that represents Windows-style paths without performing any filesystem I/O operations. It always uses backslashes (\) as path separators and supports Windows-specific features like drive letters, UNC paths, and reserved names. Use this class when you need to manipulate Windows paths on any platform.

📚 Basic Usage

Simple Example

from pathlib import PureWindowsPath

# Create Windows paths (backslashes on all platforms)
path = PureWindowsPath(r"C:\Users\john\Documents\file.txt")
config = PureWindowsPath("config") / "app.yaml"
unc_path = PureWindowsPath(r"\\server\share\data")

print(f"Path: {path}") # C:\Users\john\Documents\file.txt
print(f"Config: {config}") # config\app.yaml
print(f"UNC: {unc_path}") # \\server\share\data

# Windows-specific properties
print(f"Parts: {path.parts}") # ('C:\\', 'Users', 'john', 'Documents', 'file.txt')
print(f"Drive: {path.drive}") # C:
print(f"Root: {path.root}") # \
print(f"Anchor: {path.anchor}") # C:\

Core Methods/Functions

from pathlib import PureWindowsPath

# Path creation and manipulation
base = PureWindowsPath(r"C:\Program Files")
app_dir = base / "MyApp"
exe_path = app_dir / "myapp.exe"

print(f"Application path: {exe_path}") # C:\Program Files\MyApp\myapp.exe

# Windows drive handling
system_drive = PureWindowsPath("C:/")
data_drive = PureWindowsPath("D:/")
relative_path = PureWindowsPath("Users/john")

print(f"System drive: {system_drive}") # C:\
print(f"Data drive: {data_drive}") # D:\

# UNC (Universal Naming Convention) paths
unc_share = PureWindowsPath(r"\\fileserver\shared\documents")
print(f"UNC path: {unc_share}") # \\fileserver\shared\documents
print(f"UNC parts: {unc_share.parts}") # ('\\\\fileserver\\shared', 'documents')

Common Patterns

from pathlib import PureWindowsPath

# Pattern 1: Windows application paths
def get_windows_app_paths(app_name: str) -> dict:
"""Generate standard Windows application paths."""
return {
"program_files": PureWindowsPath(f"C:/Program Files/{app_name}"),
"program_files_x86": PureWindowsPath(f"C:/Program Files (x86)/{app_name}"),
"appdata_roaming": PureWindowsPath(f"C:/Users/{{username}}/AppData/Roaming/{app_name}"),
"appdata_local": PureWindowsPath(f"C:/Users/{{username}}/AppData/Local/{app_name}"),
"programdata": PureWindowsPath(f"C:/ProgramData/{app_name}"),
"documents": PureWindowsPath(f"C:/Users/{{username}}/Documents/{app_name}")
}

# Pattern 2: UNC path validation and parsing
def parse_unc_path(unc_str: str) -> dict:
"""Parse UNC path components."""
try:
path = PureWindowsPath(unc_str)
if not str(path).startswith("\\\\"):
return {"valid": False, "error": "Not a UNC path"}

parts = path.parts
if len(parts) < 1:
return {"valid": False, "error": "Invalid UNC format"}

# First part contains \\server\share
server_share = parts[0] # e.g., "\\\\server\\share"
path_components = parts[1:] if len(parts) > 1 else []

return {
"valid": True,
"server_share": server_share,
"path_components": list(path_components),
"full_path": str(path)
}
except Exception as e:
return {"valid": False, "error": str(e)}

# Pattern 3: Windows drive letter validation
def validate_windows_drive(drive_letter: str) -> bool:
"""Validate Windows drive letter format."""
try:
path = PureWindowsPath(f"{drive_letter}:/")
return (
len(drive_letter) == 1 and
drive_letter.isalpha() and
path.drive == f"{drive_letter.upper()}:"
)
except Exception:
return False

# Usage examples
app_paths = get_windows_app_paths("MyApplication")
for path_type, path in app_paths.items():
print(f"{path_type}: {path}")

unc_info = parse_unc_path(r"\\fileserver\documents\projects\2024")
print(f"UNC parsing: {unc_info}")

print(f"Valid drive C: {validate_windows_drive('C')}") # True
print(f"Valid drive 1: {validate_windows_drive('1')}") # False

🔧 PureWindowsPath API Reference

Constructor

MethodDescriptionParametersReturn TypeExample
PureWindowsPath(*args)Create Windows path*args: str | PurePathPureWindowsPathPureWindowsPath("C:", "Users")

Inherited Methods (from PurePath)

All methods from PurePath are available with Windows-specific behavior:

MethodWindows-Specific BehaviorExample
joinpath()Uses \ separatorpath.joinpath("dir", "file")
with_name()Preserves Windows formatpath.with_name("new.txt")
with_suffix()Preserves Windows formatpath.with_suffix(".exe")
relative_to()Windows path comparisonpath.relative_to("C:\\")
is_absolute()Checks for drive or UNCpath.is_absolute()
match()Windows shell-style patternspath.match("*.exe")

Windows-Specific Properties

PropertyDescriptionTypeExample
driveDrive letter with colonstr"C:"
rootRoot directorystr"\\"
anchorDrive + rootstr"C:\\"
partsPath components with Windows separatorstuple[str, ...]('C:\\', 'Users', 'john')

Special Methods

MethodWindows-Specific BehaviorExample
__str__()Returns Windows path string"C:\\Users\\john\\file.txt"
__truediv__()Joins with \path / "subdir"

🐛 Common Errors and Troubleshooting

Typical Error Messages

from pathlib import PureWindowsPath

# Error 1: Invalid drive letters
try:
# Invalid drive format
path = PureWindowsPath("1:\\invalid\\path")
print(path.drive) # "1:" - technically allowed but invalid in real Windows
except Exception as e:
print(f"Drive error: {e}")

# Error 2: Reserved Windows names
try:
# These are valid in PureWindowsPath but problematic in real Windows
reserved_names = ["CON", "PRN", "AUX", "NUL", "COM1", "LPT1"]
for name in reserved_names:
path = PureWindowsPath(f"C:\\temp\\{name}.txt")
print(f"Reserved name path: {path}") # Works in PurePath but fails on real filesystem
except Exception as e:
print(f"Reserved name error: {e}")

# Error 3: Path length limitations
try:
# Windows has 260 character path limit (without long path support)
long_path = "C:\\" + "a" * 250 + "\\file.txt"
path = PureWindowsPath(long_path)
print(f"Long path length: {len(str(path))}") # PurePath allows it
if len(str(path)) > 260:
print("⚠️ WARNING: Path exceeds Windows 260 character limit")
except Exception as e:
print(f"Path length error: {e}")

# Error 4: Invalid characters in Windows paths
try:
# Windows prohibits certain characters: < > : " | ? *
invalid_chars = ['<', '>', '"', '|', '?', '*']
for char in invalid_chars:
try:
path = PureWindowsPath(f"C:\\temp\\file{char}name.txt")
print(f"Path with '{char}': {path}") # PurePath might allow it
print(f"⚠️ WARNING: Character '{char}' is invalid in Windows paths")
except Exception as char_error:
print(f"Character '{char}' error: {char_error}")
except Exception as e:
print(f"Character validation error: {e}")

Debugging Tips

from pathlib import PureWindowsPath

def debug_windows_path(path_str: str):
"""Debug Windows path parsing and validation."""
try:
path = PureWindowsPath(path_str)

print(f"Input: '{path_str}'")
print(f"Parsed path: {path}")
print(f"Parts: {path.parts}")
print(f"Drive: '{path.drive}'")
print(f"Root: '{path.root}'")
print(f"Anchor: '{path.anchor}'")
print(f"Is absolute: {path.is_absolute()}")
print(f"Parent: {path.parent}")
print(f"Name: '{path.name}'")
print(f"Stem: '{path.stem}'")
print(f"Suffix: '{path.suffix}'")

# Windows-specific validations
warnings = []

# Check for UNC path
if str(path).startswith("\\\\"):
print("📁 UNC (network) path detected")

# Check for reserved names
reserved_names = {"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4",
"COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2",
"LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"}

for part in path.parts:
part_name = part.split('.')[0].upper() # Remove extension for check
if part_name in reserved_names:
warnings.append(f"Reserved Windows name: {part}")

# Check for invalid characters
invalid_chars = set('<>:"|?*')
for part in path.parts:
for char in invalid_chars:
if char in part and char != ':' or (char == ':' and part != path.drive):
warnings.append(f"Invalid character '{char}' in: {part}")

# Check path length
if len(str(path)) > 260:
warnings.append(f"Path length ({len(str(path))}) exceeds Windows limit (260)")

# Check for trailing spaces or dots
for part in path.parts:
if part.endswith(' ') or part.endswith('.'):
warnings.append(f"Trailing space/dot in: {part}")

if warnings:
print("\n⚠️ WARNINGS:")
for warning in warnings:
print(f" - {warning}")
else:
print("\n✅ Path appears valid for Windows")

except Exception as e:
print(f"❌ Error parsing path: {e}")

# Usage
debug_windows_path(r"C:\Users\john\Documents\file.txt")
debug_windows_path(r"\\server\share\documents")
debug_windows_path(r"C:\temp\CON.txt") # Reserved name
debug_windows_path(r"C:\temp\file*.txt") # Invalid character

Error Handling Patterns

from pathlib import PureWindowsPath

def safe_windows_path_join(base: str, *components: str) -> PureWindowsPath:
"""Safely join Windows path components with validation."""
try:
base_path = PureWindowsPath(base)

# Validate base path
if not base_path.is_absolute():
# Try to make it absolute by adding drive
if not base.startswith(('\\\\', '//')): # Not UNC
base_path = PureWindowsPath("C:") / base

# Clean and validate components
result_path = base_path
for component in components:
# Clean component
clean_component = str(component).strip().strip('\\/')

# Check for invalid characters
invalid_chars = set('<>"|?*')
if any(char in clean_component for char in invalid_chars):
print(f"⚠️ WARNING: Invalid characters in component: {component}")
# Remove invalid characters
for char in invalid_chars:
clean_component = clean_component.replace(char, '_')

# Check for reserved names
reserved_names = {"CON", "PRN", "AUX", "NUL"}
if clean_component.upper().split('.')[0] in reserved_names:
print(f"⚠️ WARNING: Reserved name detected: {component}")
clean_component = f"_{clean_component}"

if clean_component: # Only join non-empty components
result_path = result_path / clean_component

return result_path

except Exception as e:
print(f"Path join error: {e}")
return PureWindowsPath("C:\\") # Return safe default

def normalize_windows_path(path_str: str) -> PureWindowsPath:
"""Normalize path string to valid Windows path."""
try:
# Convert forward slashes to backslashes (except for UNC)
if not path_str.startswith('//') and not path_str.startswith('\\\\'):
normalized_str = path_str.replace('/', '\\')
else:
# Handle UNC paths
normalized_str = path_str.replace('//', '\\\\', 1).replace('/', '\\')

# Remove duplicate backslashes (except for UNC prefix)
if normalized_str.startswith('\\\\'):
# Preserve UNC prefix but clean the rest
unc_prefix = normalized_str[:2]
rest = normalized_str[2:]
while '\\\\' in rest:
rest = rest.replace('\\\\', '\\')
normalized_str = unc_prefix + rest
else:
while '\\\\' in normalized_str:
normalized_str = normalized_str.replace('\\\\', '\\')

# Create path
path = PureWindowsPath(normalized_str)

return path

except Exception as e:
print(f"Normalization error: {e}")
return PureWindowsPath("C:\\") # Return safe default

def validate_windows_path_for_filesystem(path: PureWindowsPath) -> dict:
"""Validate Windows path for actual filesystem use."""
validation_result = {
"valid": True,
"warnings": [],
"errors": []
}

path_str = str(path)

# Check path length
if len(path_str) > 260:
validation_result["errors"].append(
f"Path length ({len(path_str)}) exceeds Windows limit (260)"
)
validation_result["valid"] = False

# Check for reserved names
reserved_names = {
"CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4",
"COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2",
"LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
}

for part in path.parts:
part_name = part.split('.')[0].upper()
if part_name in reserved_names:
validation_result["errors"].append(f"Reserved Windows name: {part}")
validation_result["valid"] = False

# Check for invalid characters
invalid_chars = set('<>:"|?*')
for part in path.parts:
for char in invalid_chars:
# Allow colon only in drive specification
if char in part and not (char == ':' and part == path.drive):
validation_result["errors"].append(
f"Invalid character '{char}' in: {part}"
)
validation_result["valid"] = False

# Check for trailing spaces or dots
for part in path.parts:
if part.endswith(' '):
validation_result["warnings"].append(f"Trailing space in: {part}")
if part.endswith('.') and part != '.' and part != '..':
validation_result["warnings"].append(f"Trailing dot in: {part}")

return validation_result

# Usage
safe_path = safe_windows_path_join("C:", "Users", "john", "file*.txt")
print(f"Safe path: {safe_path}")

normalized = normalize_windows_path("C://Users//john\\Documents//file.txt")
print(f"Normalized: {normalized}")

validation = validate_windows_path_for_filesystem(
PureWindowsPath(r"C:\temp\CON.txt")
)
print(f"Validation result: {validation}")

🎯 Primary Use Cases

1. Windows Application Configuration Management

Use Case: Manage Windows application configuration paths across different user contexts Why PureWindowsPath: Windows-specific path formats, drive letters, special folders

from pathlib import PureWindowsPath
from typing import Dict, Optional
from enum import Enum

class WindowsFolder(Enum):
PROGRAM_FILES = "C:/Program Files"
PROGRAM_FILES_X86 = "C:/Program Files (x86)"
PROGRAMDATA = "C:/ProgramData"
APPDATA_ROAMING = "AppData/Roaming"
APPDATA_LOCAL = "AppData/Local"
APPDATA_LOCALLOW = "AppData/LocalLow"
DOCUMENTS = "Documents"
DESKTOP = "Desktop"
DOWNLOADS = "Downloads"
PICTURES = "Pictures"
VIDEOS = "Videos"
MUSIC = "Music"

class WindowsAppConfigManager:
"""Manage Windows application configuration paths."""

def __init__(self, app_name: str, company_name: Optional[str] = None):
self.app_name = app_name
self.company_name = company_name

# Standard Windows system paths
self.system_paths = {
"windows": PureWindowsPath("C:/Windows"),
"system32": PureWindowsPath("C:/Windows/System32"),
"program_files": PureWindowsPath("C:/Program Files"),
"program_files_x86": PureWindowsPath("C:/Program Files (x86)"),
"programdata": PureWindowsPath("C:/ProgramData"),
"temp": PureWindowsPath("C:/Temp")
}

def get_user_paths(self, username: str) -> Dict[str, PureWindowsPath]:
"""Get user-specific application paths."""
user_base = PureWindowsPath(f"C:/Users/{username}")

app_folder = self.company_name + "/" + self.app_name if self.company_name else self.app_name

return {
"profile": user_base,
"documents": user_base / "Documents" / self.app_name,
"desktop": user_base / "Desktop",
"downloads": user_base / "Downloads",

# Application data folders
"appdata_roaming": user_base / "AppData/Roaming" / app_folder,
"appdata_local": user_base / "AppData/Local" / app_folder,
"appdata_locallow": user_base / "AppData/LocalLow" / app_folder,

# Configuration files
"config_file": user_base / "AppData/Roaming" / app_folder / "config.json",
"settings_file": user_base / "AppData/Local" / app_folder / "settings.ini",
"cache_dir": user_base / "AppData/Local" / app_folder / "Cache",
"logs_dir": user_base / "AppData/Local" / app_folder / "Logs",

# User data
"user_data": user_base / "Documents" / self.app_name / "Data",
"user_projects": user_base / "Documents" / self.app_name / "Projects",
"user_exports": user_base / "Documents" / self.app_name / "Exports"
}

def get_system_installation_paths(self) -> Dict[str, PureWindowsPath]:
"""Get system-wide installation paths."""
app_folder = self.company_name + "/" + self.app_name if self.company_name else self.app_name

return {
# 64-bit installation
"install_64bit": self.system_paths["program_files"] / self.app_name,
"executable_64bit": self.system_paths["program_files"] / self.app_name / f"{self.app_name}.exe",

# 32-bit installation
"install_32bit": self.system_paths["program_files_x86"] / self.app_name,
"executable_32bit": self.system_paths["program_files_x86"] / self.app_name / f"{self.app_name}.exe",

# Shared data
"shared_data": self.system_paths["programdata"] / app_folder,
"shared_config": self.system_paths["programdata"] / app_folder / "config",
"shared_logs": self.system_paths["programdata"] / app_folder / "logs",
"shared_temp": self.system_paths["temp"] / self.app_name,

# Services and drivers
"service_exe": self.system_paths["program_files"] / self.app_name / f"{self.app_name}Service.exe",
"driver_sys": self.system_paths["system32"] / "drivers" / f"{self.app_name}.sys"
}

def get_registry_paths(self) -> Dict[str, str]:
"""Get Windows Registry paths for application settings."""
app_key = f"{self.company_name}\\{self.app_name}" if self.company_name else self.app_name

return {
# Current user settings
"hkcu_settings": f"HKEY_CURRENT_USER\\Software\\{app_key}",
"hkcu_uninstall": f"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{self.app_name}",

# Local machine settings
"hklm_settings": f"HKEY_LOCAL_MACHINE\\Software\\{app_key}",
"hklm_uninstall": f"HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{self.app_name}",
"hklm_service": f"HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services\\{self.app_name}",

# 32-bit on 64-bit (WOW64)
"hklm_wow64": f"HKEY_LOCAL_MACHINE\\Software\\WOW6432Node\\{app_key}",

# File associations
"file_association": f"HKEY_CLASSES_ROOT\\.{self.app_name.lower()}",
"shell_integration": f"HKEY_CLASSES_ROOT\\Directory\\shell\\{self.app_name}"
}

def get_startup_paths(self) -> Dict[str, PureWindowsPath]:
"""Get Windows startup and autorun paths."""
return {
# Current user startup
"user_startup": PureWindowsPath("C:/Users/{username}/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup"),
"user_run_once": "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce",

# All users startup
"all_users_startup": PureWindowsPath("C:/ProgramData/Microsoft/Windows/Start Menu/Programs/Startup"),
"system_run": "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",
"system_run_once": "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce",

# Services
"service_startup": "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services",

# Scheduled tasks
"scheduled_tasks": PureWindowsPath("C:/Windows/System32/Tasks") / self.app_name
}

def get_backup_paths(self, username: str) -> Dict[str, PureWindowsPath]:
"""Get backup paths for application data."""
user_paths = self.get_user_paths(username)
backup_base = PureWindowsPath(f"C:/Users/{username}/Documents") / f"{self.app_name}_Backup"

return {
"user_config_backup": backup_base / "Config",
"user_data_backup": backup_base / "Data",
"settings_backup": backup_base / "Settings",
"logs_backup": backup_base / "Logs",
"registry_backup": backup_base / "Registry" / f"{self.app_name}_registry.reg"
}

def generate_installer_paths(self) -> Dict[str, PureWindowsPath]:
"""Generate paths for Windows installer creation."""
return {
# Installer source files
"installer_source": PureWindowsPath("build/installer"),
"main_executable": PureWindowsPath("build/installer/bin") / f"{self.app_name}.exe",
"installer_resources": PureWindowsPath("build/installer/resources"),
"installer_scripts": PureWindowsPath("build/installer/scripts"),

# WiX (Windows Installer XML) files
"wix_source": PureWindowsPath("installer/main.wxs"),
"wix_fragments": PureWindowsPath("installer/fragments"),
"wix_output": PureWindowsPath("dist") / f"{self.app_name}_Setup.msi",

# NSIS (Nullsoft Scriptable Install System) files
"nsis_script": PureWindowsPath("installer/installer.nsi"),
"nsis_output": PureWindowsPath("dist") / f"{self.app_name}_Setup.exe",

# InnoSetup files
"inno_script": PureWindowsPath("installer/setup.iss"),
"inno_output": PureWindowsPath("dist") / f"{self.app_name}_Setup.exe"
}

# Usage
app_config = WindowsAppConfigManager("VideoEditor", "MediaSoft")

# Get user paths for specific user
user_paths = app_config.get_user_paths("john")
print("User Application Paths:")
for path_type, path in user_paths.items():
print(f" {path_type}: {path}")

# Get system installation paths
system_paths = app_config.get_system_installation_paths()
print("\nSystem Installation Paths:")
for path_type, path in system_paths.items():
print(f" {path_type}: {path}")

# Get registry paths
registry_paths = app_config.get_registry_paths()
print("\nRegistry Paths:")
for path_type, path in registry_paths.items():
print(f" {path_type}: {path}")

# Get installer paths
installer_paths = app_config.generate_installer_paths()
print("\nInstaller Paths:")
for path_type, path in installer_paths.items():
print(f" {path_type}: {path}")

2. Windows Network Share Management

Use Case: Manage UNC paths and network shares in Windows environments Why PureWindowsPath: Native UNC path support, Windows network conventions

from pathlib import PureWindowsPath
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass

@dataclass
class NetworkShare:
server: str
share_name: str
description: str
access_level: str = "read"

class WindowsNetworkManager:
"""Manage Windows UNC paths and network shares."""

def __init__(self):
# Common Windows network share patterns
self.share_types = {
"file_server": {
"shares": ["documents", "projects", "archive", "shared"],
"default_permissions": "read-write"
},
"print_server": {
"shares": ["printers", "drivers"],
"default_permissions": "read"
},
"backup_server": {
"shares": ["backups", "images", "logs"],
"default_permissions": "read"
},
"media_server": {
"shares": ["videos", "music", "images", "media"],
"default_permissions": "read"
}
}

def create_unc_path(self, server: str, share: str, *path_components: str) -> PureWindowsPath:
"""Create UNC path from server, share, and path components."""
# Ensure server name doesn't have leading backslashes
clean_server = server.lstrip("\\\\")

# Create base UNC path
unc_base = PureWindowsPath(f"\\\\{clean_server}\\{share}")

# Add path components
result_path = unc_base
for component in path_components:
if component: # Skip empty components
result_path = result_path / component

return result_path

def parse_unc_path(self, unc_path: str) -> Dict[str, Optional[str]]:
"""Parse UNC path into components."""
try:
path = PureWindowsPath(unc_path)
path_str = str(path)

if not path_str.startswith("\\\\"):
return {
"valid": False,
"error": "Not a valid UNC path",
"server": None,
"share": None,
"path_components": []
}

# Remove UNC prefix and split
without_prefix = path_str[2:] # Remove \\
parts = without_prefix.split("\\")

if len(parts) < 2:
return {
"valid": False,
"error": "UNC path must have at least server and share",
"server": None,
"share": None,
"path_components": []
}

server = parts[0]
share = parts[1]
path_components = parts[2:] if len(parts) > 2 else []

return {
"valid": True,
"error": None,
"server": server,
"share": share,
"path_components": path_components,
"full_path": path_str
}

except Exception as e:
return {
"valid": False,
"error": str(e),
"server": None,
"share": None,
"path_components": []
}

def get_department_share_paths(self, server: str, department: str) -> Dict[str, PureWindowsPath]:
"""Generate department-specific share paths."""
dept_lower = department.lower()

return {
"department_root": self.create_unc_path(server, dept_lower),
"documents": self.create_unc_path(server, dept_lower, "Documents"),
"projects": self.create_unc_path(server, dept_lower, "Projects"),
"archive": self.create_unc_path(server, dept_lower, "Archive"),
"shared": self.create_unc_path(server, dept_lower, "Shared"),
"templates": self.create_unc_path(server, dept_lower, "Templates"),
"reports": self.create_unc_path(server, dept_lower, "Reports"),
"inbox": self.create_unc_path(server, dept_lower, "Inbox"),
"outbox": self.create_unc_path(server, dept_lower, "Outbox")
}

def get_user_home_paths(self, server: str, username: str) -> Dict[str, PureWindowsPath]:
"""Generate user home directory paths on network server."""
return {
"home_root": self.create_unc_path(server, "users", username),
"documents": self.create_unc_path(server, "users", username, "Documents"),
"desktop": self.create_unc_path(server, "users", username, "Desktop"),
"downloads": self.create_unc_path(server, "users", username, "Downloads"),
"pictures": self.create_unc_path(server, "users", username, "Pictures"),
"profile": self.create_unc_path(server, "profiles", f"{username}.v6"),
"temp": self.create_unc_path(server, "temp", username)
}

def get_application_share_paths(self, server: str, app_name: str) -> Dict[str, PureWindowsPath]:
"""Generate application-specific network paths."""
app_lower = app_name.lower()

return {
"app_root": self.create_unc_path(server, "applications", app_lower),
"executables": self.create_unc_path(server, "applications", app_lower, "bin"),
"config": self.create_unc_path(server, "applications", app_lower, "config"),
"data": self.create_unc_path(server, "applications", app_lower, "data"),
"logs": self.create_unc_path(server, "applications", app_lower, "logs"),
"backups": self.create_unc_path(server, "backups", app_lower),
"updates": self.create_unc_path(server, "updates", app_lower),
"shared_data": self.create_unc_path(server, "shared", app_lower)
}

def generate_dfs_paths(self, domain: str, dfs_root: str) -> Dict[str, PureWindowsPath]:
"""Generate Distributed File System (DFS) paths."""
return {
"dfs_root": PureWindowsPath(f"\\\\{domain}\\{dfs_root}"),
"users": PureWindowsPath(f"\\\\{domain}\\{dfs_root}\\Users"),
"departments": PureWindowsPath(f"\\\\{domain}\\{dfs_root}\\Departments"),
"applications": PureWindowsPath(f"\\\\{domain}\\{dfs_root}\\Applications"),
"shared": PureWindowsPath(f"\\\\{domain}\\{dfs_root}\\Shared"),
"archive": PureWindowsPath(f"\\\\{domain}\\{dfs_root}\\Archive"),
"public": PureWindowsPath(f"\\\\{domain}\\{dfs_root}\\Public")
}

def get_backup_share_paths(self, backup_server: str, client_name: str) -> Dict[str, PureWindowsPath]:
"""Generate backup share paths for a client."""
client_lower = client_name.lower()

return {
"client_root": self.create_unc_path(backup_server, "backups", client_lower),
"daily": self.create_unc_path(backup_server, "backups", client_lower, "daily"),
"weekly": self.create_unc_path(backup_server, "backups", client_lower, "weekly"),
"monthly": self.create_unc_path(backup_server, "backups", client_lower, "monthly"),
"system_state": self.create_unc_path(backup_server, "backups", client_lower, "system_state"),
"user_data": self.create_unc_path(backup_server, "backups", client_lower, "user_data"),
"applications": self.create_unc_path(backup_server, "backups", client_lower, "applications"),
"logs": self.create_unc_path(backup_server, "backups", client_lower, "logs")
}

def validate_unc_path_format(self, unc_path: str) -> Dict[str, any]:
"""Validate UNC path format and naming conventions."""
validation_result = {
"valid": True,
"warnings": [],
"errors": []
}

try:
path = PureWindowsPath(unc_path)
path_str = str(path)

# Check UNC format
if not path_str.startswith("\\\\"):
validation_result["errors"].append("Path must start with \\\\")
validation_result["valid"] = False
return validation_result

# Parse components
parsed = self.parse_unc_path(unc_path)
if not parsed["valid"]:
validation_result["errors"].append(parsed["error"])
validation_result["valid"] = False
return validation_result

server = parsed["server"]
share = parsed["share"]

# Validate server name
if not server:
validation_result["errors"].append("Server name is required")
validation_result["valid"] = False
elif len(server) > 15:
validation_result["warnings"].append(
f"Server name '{server}' is longer than 15 characters (NetBIOS limit)"
)

# Validate share name
if not share:
validation_result["errors"].append("Share name is required")
validation_result["valid"] = False
elif len(share) > 80:
validation_result["errors"].append(
f"Share name '{share}' exceeds 80 character limit"
)
validation_result["valid"] = False

# Check for invalid characters in server and share
invalid_chars = set('<>:"|?*')
for char in invalid_chars:
if char in server:
validation_result["errors"].append(
f"Invalid character '{char}' in server name"
)
validation_result["valid"] = False
if char in share:
validation_result["errors"].append(
f"Invalid character '{char}' in share name"
)
validation_result["valid"] = False

# Check path length
if len(path_str) > 260:
validation_result["warnings"].append(
f"Path length ({len(path_str)}) may exceed Windows limits"
)

# Check for administrative shares
admin_shares = {"C$", "D$", "E$", "ADMIN$", "IPC$", "PRINT$"}
if share.upper() in admin_shares:
validation_result["warnings"].append(
f"'{share}' is an administrative share"
)

except Exception as e:
validation_result["errors"].append(f"Path parsing error: {e}")
validation_result["valid"] = False

return validation_result

# Usage
network_mgr = WindowsNetworkManager()

# Create UNC paths
file_server_path = network_mgr.create_unc_path("fileserver01", "documents", "projects", "2024")
print(f"UNC path: {file_server_path}")

# Parse UNC path
parsed = network_mgr.parse_unc_path(r"\\fileserver01\documents\projects\2024\project1")
print(f"Parsed UNC: {parsed}")

# Get department paths
it_paths = network_mgr.get_department_share_paths("deptserver", "IT")
print("\nIT Department Paths:")
for path_type, path in it_paths.items():
print(f" {path_type}: {path}")

# Get user home paths
user_paths = network_mgr.get_user_home_paths("homeserver", "jsmith")
print("\nUser Home Paths:")
for path_type, path in user_paths.items():
print(f" {path_type}: {path}")

# Generate DFS paths
dfs_paths = network_mgr.generate_dfs_paths("company.local", "shares")
print("\nDFS Paths:")
for path_type, path in dfs_paths.items():
print(f" {path_type}: {path}")

# Validate UNC path
validation = network_mgr.validate_unc_path_format(r"\\fileserver01\invalid<share\file.txt")
print(f"\nValidation result: {validation}")

🎯 When to Use pathlib.PureWindowsPath

✅ Ideal Use Cases

  • Windows application development on any platform
  • UNC path manipulation for network shares and resources
  • Windows installer generation and deployment scripting
  • Registry path management and Windows configuration
  • Cross-platform development targeting Windows deployment
  • PowerShell script generation from Python
  • Windows-specific file handling (drive letters, reserved names)
  • Group Policy path management and Active Directory integration

❌ When NOT to Use pathlib.PureWindowsPath

  • Unix/Linux specific applications (use PurePosixPath instead)
  • Need actual filesystem I/O (use WindowsPath instead)
  • Platform-agnostic applications (use Path for auto-detection)
  • URL manipulation (URLs use forward slashes like POSIX)

Alternative Solutions

  • pathlib.PurePosixPath: For Unix/Linux-specific path manipulation
  • pathlib.Path: For filesystem I/O operations (auto-selects platform)
  • pathlib.WindowsPath: For Windows paths with filesystem operations
  • os.path.nt: Legacy Windows path operations
  • ntpath: Lower-level Windows path manipulation

Additional Learning Resources

Official Python Resources

Windows-Specific Documentation

  • Windows PowerShell path management
  • Active Directory integration
  • Windows installer development (WiX, NSIS, InnoSetup)
  • Windows services and system integration