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_asciiisTrue(the default),dump()anddumps()output keys & values in pure ASCII; non-ASCII and unprintable characters are escaped with the escape sequences listed above. Whenensure_asciiisFalse, the functions instead pass all non-ASCII characters through as-is; unprintable characters are still escaped.When
ensure_ascii_commentsisNone(the default),dump()anddumps()output thecommentsargument (if set) using only Latin-1 (ISO-8859-1) characters; all other characters are escaped. Whenensure_ascii_commentsisTrue, the functions instead escape all non-ASCII characters incomments. Whenensure_ascii_commentsisFalse, the functions instead pass all characters incommentsthrough as-is.Note that, in order to match the behavior of Java’s
Propertiesclass, unprintable ASCII characters incommentsare always passed through as-is rather than escaped.Newlines inside
commentsare 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: Mapping[str, str] | Iterable[tuple[str, str]], fp: TextIO, separator: str = '=', comments: str | None = None, timestamp: None | bool | float | datetime = True, sort_keys: bool = False, ensure_ascii: bool = True, ensure_ascii_comments: bool | None = None) None[source]
Write a series of key-value pairs to a file in simple line-oriented
.propertiesformat.Changed in version 0.6.0:
ensure_asciiandensure_ascii_commentsparameters added- Parameters:
props – A mapping or iterable of
(key, value)pairs to write tofp. All keys and values inpropsmust bestrvalues. Ifsort_keysisFalse, the entries are output in iteration order.fp (TextIO) – A file-like object to write the values of
propsto. 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,commentswill be written tofpas a comment before any other contenttimestamp (
None,bool, number, ordatetime.datetime) – If neitherNonenorFalse, a timestamp in the form ofMon Sep 02 14:00:54 EDT 2016is written as a comment tofpaftercomments(if any) and before the key-value pairs. IftimestampisTrue, 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 adatetime.datetimeobject, its value is used directly, with naïve objects assumed to be in the local timezone.sort_keys (bool) – if true, the elements of
propsare sorted lexicographically by key in the outputensure_ascii (bool) – if true, all non-ASCII characters will be replaced with
\uXXXXescape sequences in the output; if false, non-ASCII characters will be passed through as-isensure_ascii_comments (Optional[bool]) – if true, all non-ASCII characters in
commentswill be replaced with\uXXXXescape sequences in the output; ifNone, only non-Latin-1 characters will be escaped; if false, no characters will be escaped
- Returns:
- javaproperties.dumps(props: Mapping[str, str] | Iterable[tuple[str, str]], separator: str = '=', comments: str | None = None, timestamp: None | bool | float | datetime = True, sort_keys: bool = False, ensure_ascii: bool = True, ensure_ascii_comments: bool | None = None) str[source]
Convert a series of key-value pairs to a
strin simple line-oriented.propertiesformat.Changed in version 0.6.0:
ensure_asciiandensure_ascii_commentsparameters added- Parameters:
props – A mapping or iterable of
(key, value)pairs to serialize. All keys and values inpropsmust bestrvalues. Ifsort_keysisFalse, 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,commentswill be output as a comment before any other contenttimestamp (
None,bool, number, ordatetime.datetime) – If neitherNonenorFalse, a timestamp in the form ofMon Sep 02 14:00:54 EDT 2016is output as a comment aftercomments(if any) and before the key-value pairs. IftimestampisTrue, 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 adatetime.datetimeobject, its value is used directly, with naïve objects assumed to be in the local timezone.sort_keys (bool) – if true, the elements of
propsare sorted lexicographically by key in the outputensure_ascii (bool) – if true, all non-ASCII characters will be replaced with
\uXXXXescape sequences in the output; if false, non-ASCII characters will be passed through as-isensure_ascii_comments (Optional[bool]) – if true, all non-ASCII characters in
commentswill be replaced with\uXXXXescape sequences in the output; ifNone, 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 objectfpas a simple line-oriented.propertiesfile and return adictof the key-value pairs.fpmay 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
fpare combined into adictwith later occurrences of a key overriding previous occurrences of the same key. To change this behavior, pass a callable as theobject_pairs_hookargument; it will be called with one argument, a generator of(key, value)pairs representing the key-value entries infp(including duplicates) in order of occurrence.loadwill then return the value returned byobject_pairs_hook.Changed in version 0.5.0: Invalid
\uXXXXescape sequences will now cause anInvalidUEscapeErrorto be raised- Parameters:
fp (IO) – the file from which to read the
.propertiesdocumentobject_pairs_hook (callable) – class or function for combining the key-value pairs
- Return type:
dictof text strings or the return value ofobject_pairs_hook- Raises:
InvalidUEscapeError – if an invalid
\uXXXXescape sequence occurs in the input
- javaproperties.loads(s: str | bytes) dict[str, str][source]
- javaproperties.loads(s: str | bytes, object_pairs_hook: type[T]) T
- javaproperties.loads(s: str | bytes, object_pairs_hook: Callable[[Iterator[tuple[str, str]]], T]) T
Parse the contents of the string
sas a simple line-oriented.propertiesfile and return adictof the key-value pairs.smay 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
sare combined into adictwith later occurrences of a key overriding previous occurrences of the same key. To change this behavior, pass a callable as theobject_pairs_hookargument; it will be called with one argument, a generator of(key, value)pairs representing the key-value entries ins(including duplicates) in order of occurrence.loadswill then return the value returned byobject_pairs_hook.Changed in version 0.5.0: Invalid
\uXXXXescape sequences will now cause anInvalidUEscapeErrorto be raised- Parameters:
- Return type:
dictof text strings or the return value ofobject_pairs_hook- Raises:
InvalidUEscapeError – if an invalid
\uXXXXescape sequence occurs in the input