Simple Line-Oriented .properties Format

Format Overview

The simple line-oriented .properties file format consists of a series of key-value string pairs, one (or fewer) per line, with the key & value separated by the first occurrence of an equals sign (=, optionally with surrounding whitespace), a colon (:, optionally with surrounding whitespace), or non-leading whitespace. A line without a separator is treated as a key whose value is the empty string. If the same key occurs more than once in a single file, only its last value is used.

Note

Lines are terminated by \n (LF), \r\n (CR LF), or \r (CR).

Note

For the purposes of this format, only the space character (ASCII 0x20), the tab character (ASCII 0x09), and the form feed character (ASCII 0x0C) count as whitespace.

Leading whitespace on a line is ignored, but trailing whitespace (after stripping trailing newlines) is not. Lines whose first non-whitespace character is # or ! (not escaped) are comments and are ignored.

Entries can be extended across multiple lines by ending all but the last line with a backslash; the backslash, the line ending after it, and any leading whitespace on the next line will all be discarded. A backslash at the end of a comment line has no effect. A comment line after a line that ends with a backslash is treated as part of a normal key-value entry, not as a comment.

Occurrences of =, :, #, !, and whitespace inside a key or value are escaped with a backslash. In addition, the following escape sequences are recognized:

\t \n \f \r \uXXXX \\

Unicode characters outside the Basic Multilingual Plane can be represented by a pair of \uXXXX escape sequences encoding the corresponding UTF-16 surrogate pair.

If a backslash is followed by character other than those listed above, the backslash is discarded.

An example simple line-oriented .properties file:

#This is a comment.
foo=bar
baz: quux
gnusto cleesh
snowman = \u2603
goat = \ud83d\udc10
novalue
host\:port=127.0.0.1\:80

This corresponds to the Python dict:

{
    "foo": "bar",
    "baz": "quux",
    "gnusto": "cleesh",
    "snowman": "☃",
    "goat": "🐐",
    "novalue": "",
    "host:port": "127.0.0.1:80",
}

File Encoding

Although the load() and loads() functions accept arbitrary Unicode characters in their input, by default the dump() and dumps() functions limit the characters in their output as follows:

  • When ensure_ascii is True (the default), dump() and dumps() output keys & values in pure ASCII; non-ASCII and unprintable characters are escaped with the escape sequences listed above. When ensure_ascii is False, the functions instead pass all non-ASCII characters through as-is; unprintable characters are still escaped.

  • When ensure_ascii_comments is None (the default), dump() and dumps() output the comments argument (if set) using only Latin-1 (ISO-8859-1) characters; all other characters are escaped. When ensure_ascii_comments is True, the functions instead escape all non-ASCII characters in comments. When ensure_ascii_comments is False, the functions instead pass all characters in comments through as-is.

    • Note that, in order to match the behavior of Java’s Properties class, unprintable ASCII characters in comments are always passed through as-is rather than escaped.

    • Newlines inside comments are not escaped, but a # is inserted after every one not already followed by a # or !.

When writing properties to a file, you must either (a) open the file using an encoding that supports all of the characters in the formatted output or else (b) open the file using the ‘javapropertiesreplace’ error handler defined by this module. The latter option allows one to write valid simple-format properties files in any encoding without having to worry about whether the properties or comment contain any characters not representable in the encoding.

Functions

javaproperties.dump(props: Union[Mapping[str, str], Iterable[Tuple[str, str]]], fp: TextIO, separator: str = '=', comments: Optional[str] = None, timestamp: Union[None, bool, float, datetime.datetime] = True, sort_keys: bool = False, ensure_ascii: bool = True, ensure_ascii_comments: Optional[bool] = None)None[source]

Write a series of key-value pairs to a file in simple line-oriented .properties format.

Changed in version 0.6.0: ensure_ascii and ensure_ascii_comments parameters added

Parameters
  • props – A mapping or iterable of (key, value) pairs to write to fp. All keys and values in props must be str values. If sort_keys is False, the entries are output in iteration order.

  • fp (TextIO) – A file-like object to write the values of props to. It must have been opened as a text file.

  • separator (str) – The string to use for separating keys & values. Only " ", "=", and ":" (possibly with added whitespace) should ever be used as the separator.

  • comments (Optional[str]) – if non-None, comments will be written to fp as a comment before any other content

  • timestamp (None, bool, number, or datetime.datetime) – If neither None nor False, a timestamp in the form of Mon Sep 02 14:00:54 EDT 2016 is written as a comment to fp after comments (if any) and before the key-value pairs. If timestamp is True, the current date & time is used. If it is a number, it is converted from seconds since the epoch to local time. If it is a datetime.datetime object, its value is used directly, with naïve objects assumed to be in the local timezone.

  • sort_keys (bool) – if true, the elements of props are sorted lexicographically by key in the output

  • ensure_ascii (bool) – if true, all non-ASCII characters will be replaced with \uXXXX escape sequences in the output; if false, non-ASCII characters will be passed through as-is

  • ensure_ascii_comments (Optional[bool]) – if true, all non-ASCII characters in comments will be replaced with \uXXXX escape sequences in the output; if None, only non-Latin-1 characters will be escaped; if false, no characters will be escaped

Returns

None

javaproperties.dumps(props: Union[Mapping[str, str], Iterable[Tuple[str, str]]], separator: str = '=', comments: Optional[str] = None, timestamp: Union[None, bool, float, datetime.datetime] = True, sort_keys: bool = False, ensure_ascii: bool = True, ensure_ascii_comments: Optional[bool] = None)str[source]

Convert a series of key-value pairs to a str in simple line-oriented .properties format.

Changed in version 0.6.0: ensure_ascii and ensure_ascii_comments parameters added

Parameters
  • props – A mapping or iterable of (key, value) pairs to serialize. All keys and values in props must be str values. If sort_keys is False, the entries are output in iteration order.

  • separator (str) – The string to use for separating keys & values. Only " ", "=", and ":" (possibly with added whitespace) should ever be used as the separator.

  • comments (Optional[str]) – if non-None, comments will be output as a comment before any other content

  • timestamp (None, bool, number, or datetime.datetime) – If neither None nor False, a timestamp in the form of Mon Sep 02 14:00:54 EDT 2016 is output as a comment after comments (if any) and before the key-value pairs. If timestamp is True, the current date & time is used. If it is a number, it is converted from seconds since the epoch to local time. If it is a datetime.datetime object, its value is used directly, with naïve objects assumed to be in the local timezone.

  • sort_keys (bool) – if true, the elements of props are sorted lexicographically by key in the output

  • ensure_ascii (bool) – if true, all non-ASCII characters will be replaced with \uXXXX escape sequences in the output; if false, non-ASCII characters will be passed through as-is

  • ensure_ascii_comments (Optional[bool]) – if true, all non-ASCII characters in comments will be replaced with \uXXXX escape sequences in the output; if None, only non-Latin-1 characters will be escaped; if false, no characters will be escaped

Return type

text string

javaproperties.load(fp: IO)Dict[str, str][source]
javaproperties.load(fp: IO, object_pairs_hook: Type[T])T
javaproperties.load(fp: IO, object_pairs_hook: Callable[[Iterator[Tuple[str, str]]], T])T

Parse the contents of the readline-supporting file-like object fp as a simple line-oriented .properties file and return a dict of the key-value pairs.

fp may be either a text or binary filehandle, with or without universal newlines enabled. If it is a binary filehandle, its contents are decoded as Latin-1.

By default, the key-value pairs extracted from fp are combined into a dict with later occurrences of a key overriding previous occurrences of the same key. To change this behavior, pass a callable as the object_pairs_hook argument; it will be called with one argument, a generator of (key, value) pairs representing the key-value entries in fp (including duplicates) in order of occurrence. load will then return the value returned by object_pairs_hook.

Changed in version 0.5.0: Invalid \uXXXX escape sequences will now cause an InvalidUEscapeError to be raised

Parameters
  • fp (IO) – the file from which to read the .properties document

  • object_pairs_hook (callable) – class or function for combining the key-value pairs

Return type

dict of text strings or the return value of object_pairs_hook

Raises

InvalidUEscapeError – if an invalid \uXXXX escape sequence occurs in the input

javaproperties.loads(s: Union[str, bytes])Dict[str, str][source]
javaproperties.loads(s: Union[str, bytes], object_pairs_hook: Type[T])T
javaproperties.loads(s: Union[str, bytes], object_pairs_hook: Callable[[Iterator[Tuple[str, str]]], T])T

Parse the contents of the string s as a simple line-oriented .properties file and return a dict of the key-value pairs.

s may be either a text string or bytes string. If it is a bytes string, its contents are decoded as Latin-1.

By default, the key-value pairs extracted from s are combined into a dict with later occurrences of a key overriding previous occurrences of the same key. To change this behavior, pass a callable as the object_pairs_hook argument; it will be called with one argument, a generator of (key, value) pairs representing the key-value entries in s (including duplicates) in order of occurrence. loads will then return the value returned by object_pairs_hook.

Changed in version 0.5.0: Invalid \uXXXX escape sequences will now cause an InvalidUEscapeError to be raised

Parameters
  • s (Union[str,bytes]) – the string from which to read the .properties document

  • object_pairs_hook (callable) – class or function for combining the key-value pairs

Return type

dict of text strings or the return value of object_pairs_hook

Raises

InvalidUEscapeError – if an invalid \uXXXX escape sequence occurs in the input