Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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, 2025 by avibootz
...