0

I want to fix this function so that special characters are replaced with a similar legal character or in case that's too complex removed depending on the os.

Is there a simple way to do that or should I just do something like?

value = "".join(c for c in meta[key] if c.isalnum() or c in " -._")
value = " ".join(value.split())

def build_folder_tree(tree: str, meta: Dict) -> str:
    """
    Build a folder tree from a metadata dictionary
    """
    path = ""
    for key in tree.split(os.sep):
        if key not in meta or not meta[key]:
            continue
        value = meta[key]
        if isinstance(value, list):
            value = meta[key][0]
        path = os.path.join(path, value)
    return path

edit: I think I'll use pathvalidate package because it can check automatically for the current os.

  • Does this answer your question? [Check whether a path is valid in Python without creating a file at the path's target](https://stackoverflow.com/questions/9532499/check-whether-a-path-is-valid-in-python-without-creating-a-file-at-the-paths-ta) – match Sep 10 '22 at 17:35
  • I want to make it valid, no need to check the validity. –  Sep 10 '22 at 17:40
  • The pathlib is a good way to deal with path for different os's – Module_art Sep 10 '22 at 17:45
  • I know, I'm using it, but I don't think it has an option to replace illegal characters. –  Sep 10 '22 at 17:48
  • try regex to parse your string before forward onto Pathlib – Module_art Sep 10 '22 at 17:54

0 Answers0