How to simplify path (remove ".." and "." and replace multiple “////” with one single “/”) in Python

1 Answer

0 votes
# Function to simplify a Unix-style file path
def simplify_path(path: str) -> str:
    stack = []  # Stack to store valid directory names
    result = ""  # Final simplified path
    psize = len(path)  # Length of the input path
    i = 0

    # Iterate through each character in the path
    while i < psize:
        if path[i] == '/':
            i += 1
            continue  # Skip redundant slashes

        pathpart = ""

        # Extract the next pathpart until the next slash
        while i < psize and path[i] != '/':
            pathpart += path[i]
            i += 1

        # Ignore current pathpart references
        if pathpart == ".":
            continue

        # Handle parent pathpart reference
        elif pathpart == "..":
            # Ignore ".." instead of popping
            continue

        # Valid pathpart, push to stack
        else:
            stack.append(pathpart)

    # Reconstruct the simplified path from the stack
    while stack:
        result = "/" + stack.pop() + result

    # If the stack was empty, return root directory
    return result if result else "/"


# Input path to be simplified
input_path = "/home//foo/../bar/./unix/"

# Call the simplify_path function
simplified = simplify_path(input_path)

# Output the result
print("Simplified path:", simplified)



'''
run:

Simplified path: /home/foo/bar/unix

'''



 



answered Sep 8 by avibootz
...