Created
July 4, 2025 01:43
-
-
Save yeiichi/06cae2f3f04ef45c25a76a13a7fccb9c to your computer and use it in GitHub Desktop.
Extract the parent directory path from the given file path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from urllib.parse import urlparse, urlunparse, ParseResult | |
# Constants | |
ROOT_PATH = '/' | |
def extract_parent_path(path: str) -> str: | |
""" | |
Extracts the parent directory path from the given file path. | |
This function receives a file or directory path, trims trailing slashes, and returns the parent directory | |
path. If the input path resolves to the root level, a predefined root path is returned. | |
Args: | |
path (str): The input file or directory path. | |
Returns: | |
str: The parent directory path. | |
""" | |
return '/'.join(path.rstrip('/').split('/')[:-1]) or ROOT_PATH | |
def get_parent_url(url): | |
"""Get the parent URL by removing the last segment of the path.""" | |
parsed_url = urlparse(url) | |
parent_path = extract_parent_path(parsed_url.path) | |
updated_url: ParseResult = parsed_url._replace(path=parent_path) | |
return urlunparse(updated_url) | |
if __name__ == '__main__': | |
input_url = input('URL?: ').strip() | |
parent_url = get_parent_url(input_url) | |
print(f"Parent URL: {parent_url}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment