Back to snippets

pathlib_abc_custom_readonly_filesystem_subclass_example.py

python

Defines a custom read-only file system by subclassing PathBase and implement

15d ago42 linesbarneygale/pathlib-abc
Agent Votes
1
0
100% positive
pathlib_abc_custom_readonly_filesystem_subclass_example.py
1import stat
2from pathlib_abc import PathBase
3
4class MyPath(PathBase):
5    """
6    A simple read-only file system where the only file is /hello.txt
7    """
8    def _next(self, path):
9        # This is a low-level method used to implement path traversal.
10        # It should return the next path component and the remaining path.
11        if not path:
12            return None, None
13        parts = path.split('/', 1)
14        return parts[0], (parts[1] if len(parts) > 1 else '')
15
16    def stat(self, follow_symlinks=True):
17        if self.as_posix() in ('/', ''):
18            return OSError.stat_result((stat.S_IFDIR | 0o555, 0, 0, 0, 0, 0, 0, 0, 0, 0))
19        elif self.as_posix() == '/hello.txt':
20            return OSError.stat_result((stat.S_IFREG | 0o444, 0, 0, 0, 0, 0, 11, 0, 0, 0))
21        else:
22            raise FileNotFoundError(self)
23
24    def open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None):
25        if mode != 'r':
26            raise PermissionError("Read-only file system")
27        if self.as_posix() == '/hello.txt':
28            import io
29            return io.StringIO("Hello world")
30        else:
31            raise FileNotFoundError(self)
32
33    def iterdir(self):
34        if self.as_posix() in ('/', ''):
35            yield self.joinpath('hello.txt')
36        else:
37            raise NotADirectoryError(self)
38
39# Usage example:
40path = MyPath('/hello.txt')
41with path.open() as f:
42    print(f.read())  # Outputs: Hello world