files.py 2.01 KB
Newer Older
Matteo's avatar
update    
Matteo committed
1
2
from io import TextIOWrapper
from enum import Enum
Matteo's avatar
Matteo committed
3
4
import json
import yaml
Matteo's avatar
update    
Matteo committed
5
from pydantic import BaseModel
Matteo's avatar
Matteo committed
6
7


Matteo's avatar
update    
Matteo committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class FileAction(Enum):
    READ = "r"
    WRITE = "w"
    APPEND = "a"


class FileType(Enum):
    YAML = "yaml"
    JSON = "json"


class File(BaseModel):
    encoding: str
    format: FileType
    path: str

    def __init__(self, path: str, filetype: FileType, encoding: str = 'utf-8'):
        super().__init__(path=path, format=filetype, encoding=encoding)

    def open(self, action: FileAction) -> TextIOWrapper:
        """
        Open the file with the given action        

        Parameters
        ----------
        action : FileAction
            the action to perform on the file at opening

        Returns
        -------
        TextIOWrapper
            the file descriptor
        """
        return open(self.path, action.value, encoding=self.encoding)

    def get_content(self) -> dict:
        """
        Return the file content

        Raises
        ------
        ValueError
            if the format is not supported
        
        Returns
        -------
        dict
            the parsed content of the file
        """
        with self.open(FileAction.READ) as fd:
            if self.format == FileType.YAML:
                content = yaml.safe_load(fd)
                return content
            if self.format == FileType.JSON:
                content = json.load(fd)
            else:
                raise ValueError("Format not supported")

        return content

    def write_content(self, content: dict) -> None:
        """
        Write the given content in the file

        Parameters
        ----------
        content : dict
            the content to write in the file
        """
        with self.open(FileAction.WRITE) as fd:
            if self.format == FileType.YAML:
                yaml.safe_dump(content, fd)
            elif self.format == FileType.JSON:
Matteo's avatar
update    
Matteo committed
81
                json.dump(content, fd, indent=4)
Matteo's avatar
update    
Matteo committed
82
83
            else:
                raise ValueError("Format not supported")