Python library that represents file paths as a tree structure

Hello,

I am trying to create a FUSE filesystem implemented in Python. For this filesystem I need to be able to translate parts of a path from cryptic IDs into something more understandable to the end user.

Right now I am doing that using regex but I would like to transition to something more robust. The idea is to keep the path in a tree-like structure and keep a real_name and fake_name in each node in order to be able to translate between the real and the fake paths depending on the operation.

Are you aware of any libraries or examples that implement such a path structure to base-of of or give me a starting point?

Posted Mar 16, 2021, 3:14 PM UTC

65
kyberborn again programmer, just for fun this time•

If you haven't already, it is worth looking at pathlib's representation:

https://docs.python.org/3/library/pathlib.html

https://realpython.com/python-pathlib/

3
synthphreak•

+10 for pathlib

1
loathingkernelOP•

Thank you for the suggestion. I had looked at pathlib, and while I can't say I understand its internals yet, it doesn't seem to be close to what I was thinking of. On the other hand, I might have been thinking of the wrong way to go about it to begin with so I will take a deeper look again.

1
misho88•

I'm not sure it'd be worth creating a library for something like this. You can just use a dictionary or something:

$ tree
.
├── d1
│   ├── d1.1
│   │   ├── f1.1.1
│   │   └── f1.1.2
│   └── f1.1
├── d2
└── f1

3 directories, 4 files
$ bpython
bpython version 0.20 on top of Python 3.9.2 /usr/bin/python
>>> from pathlib import Path
>>> def hierarchy(root: Path):
...     return { child: hierarchy(child) for child in root.iterdir() } if root.is_dir() else None
... 
>>> from pprint import pprint
>>> pprint(hierarchy(Path('.')))
{PosixPath('d1'): {PosixPath('d1/d1.1'): {PosixPath('d1/d1.1/f1.1.1'): None,
                                          PosixPath('d1/d1.1/f1.1.2'): None},
                   PosixPath('d1/f1.1'): None},
 PosixPath('d2'): {},
 PosixPath('f1'): None}
2
loathingkernelOP•

Thank you for the example. I tried doing something similar but probably didn't do it properly. I think I can get a workable solution from your example!

1