[Python] How to properly escape UNC paths for string literals in Python while avoiding double...

Discussão em 'Python' iniciado por Stack, Agosto 1, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a Python function that converts Windows file paths to UNC extended-length format and properly escapes them for string literal representation in configuration files. However, I'm running into issues with detecting existing UNC prefixes and avoiding double-escaping.

    Here is what I've tried

    def convert_to_unc_path(path: str) -> str:
    if path.startswith(r"\\?\\"):
    normalized = path
    else:
    normalized = r"\\?\\" + path

    # Escape all backslashes for string literal representation
    escaped = normalized.replace("\\", "\\\\")
    return escaped


    Here is my input details

    input_path = r"\\?\C:\Windows\system32\config\systemprofile\AppData\Local\temp\p\package_abc123\p"
    expected_path = r"\\\\?\\C:\\Windows\\system32\\config\\systemprofile\\AppData\\Local\\temp\\p\\package_abc123\\p"

    result = convert_to_unc_path(input_path)
    print("Input:", repr(input_path))
    print("Expected:", repr(expected_path))
    print("Actual:", repr(result))
    print("Match:", result == expected_path)


    I'm escaping it too many times? Would love some input

    Continue reading...

Compartilhe esta Página