Ejemplo n.º 1
0
def loads(data: str, **kwargs) -> dict:
    """Creates a dictionary of key value pairs from a key value pair string.

    The string is expected to contain key value pairs that are separated by new line characters,
    as if they were read from a file of the following format:
    key=value
    key2=value

    Args:
        data: Data from the read file.

    Keyword Args:
        comment: If the file contains lines with comments after data, everything after this character
                 will be stripped
    """
    ret = {}
    new_data = makestr(data.replace('\r\n', '\n')).split('\n')
    if new_data:
        for line in new_data:
            new_line = line.strip()
            if new_line and new_line[0] not in _COMMENT_CHECKS and '=' in new_line:
                inline_comment_symbol = kwargs.get('comment')
                if inline_comment_symbol:
                    line = new_line.split(inline_comment_symbol, 1)
                    key, value = line[0].split('=', 1)
                else:
                    key, value = new_line.split('=', 1)
                ret[key.strip()] = value.strip()

    return ret
Ejemplo n.º 2
0
def dumps(data: dict, **kwargs) -> str:
    """Dumps a dictionary to a key/value pair string for writing to a file.

    Args:
        data: dictionary to convert to key/value pair string

    Keyword Args:
        spaced: Add a space around the equals sign separating the key and value

    Raises:
        TypeError: A value is a dictionary, set, or list
    """
    ret = ''
    equals_str = '=' if not kwargs.get('spaced', False) else ' = '

    for key, value in data.items():
        value_type = type(value)
        if value_type in {dict, list, set}:
            raise TypeError(f"value for key '{key}' is a {value_type}")
        ret += makestr(key) + equals_str + makestr(value) + '\n'

    return ret.strip()
Ejemplo n.º 3
0
def file_write(path: str,
               data: AnyStr,
               backup: bool = False,
               newline: str = None) -> None:
    """Write ``data`` to a file

    Args:
        path: Full path to the file to write `data` to.
        data: Data to write to ``path``
        backup: Backup the file before writing to it. (Default is False.)
        newline: Passed to the open function for newline translation. The default
            of None lets native translation happen.
    """
    mode = 'a' if not os.path.isfile(path) else 'w'

    if backup:
        backup_path(path)

    LOGGER.debug("Write to file: %s", path)
    with open(path, mode, newline=newline, encoding='utf8') as open_file:
        total_chars = open_file.write(makestr(data))
        LOGGER.debug("Wrote %d characters", total_chars)
Ejemplo n.º 4
0
 def test_makestr_utf8(self):
     self.assertEqual(strings.makestr(str("tests").encode("UTF-8")),
                      str("tests"))
Ejemplo n.º 5
0
 def test_makestr_str(self):
     self.assertEqual(strings.makestr(str("tests")), str("tests"))