PropertiesFile Class
- class javaproperties.PropertiesFile(mapping: None | Mapping[str, str] | Iterable[tuple[str, str]] = None, **kwargs: str)[source]
Added in version 0.3.0.
A custom mapping class for reading from, editing, and writing to a
.propertiesfile while preserving comments & whitespace in the original input.A
PropertiesFileinstance can be constructed from another mapping and/or iterable of pairs, after which it will act like anOrderedDict. Alternatively, an instance can be constructed from a file or string withPropertiesFile.load()orPropertiesFile.loads(), and the resulting instance will remember the formatting of its input and retain that formatting when written back to a file or string with thedump()ordumps()method. The formatting information attached to an instancepfcan be forgotten by constructing another mapping from it viadict(pf),OrderedDict(pf), or evenPropertiesFile(pf)(Use thecopy()method if you want to create anotherPropertiesFileinstance with the same data & formatting).When not reading or writing,
PropertiesFilebehaves like a normalMutableMappingclass (i.e., you can doprops[key] = valueand so forth), except that (a) likeOrderedDict, key insertion order is remembered and is used when iterating & dumping (andreversedis supported), and (b) likeProperties, it may only be used to store strings and will raise aTypeErrorif passed a non-string object as key or value.Two
PropertiesFileinstances compare equal iff both their key-value pairs and comment & whitespace lines are equal and in the same order. When comparing aPropertiesFileto any other type of mapping, only the key-value pairs are considered, and order is ignored.PropertiesFilecurrently only supports reading & writing the simple line-oriented format, not XML.- copy() PropertiesFile[source]
Create a copy of the mapping, including formatting information
- dump(fp: TextIO, separator: str = '=', ensure_ascii: bool = True) None[source]
Write the mapping to a file in simple line-oriented
.propertiesformat.If the instance was originally created from a file or string with
PropertiesFile.load()orPropertiesFile.loads(), then the output will include the comments and whitespace from the original input, and any keys that haven’t been deleted or reassigned will retain their original formatting and multiplicity. Key-value pairs that have been modified or added to the mapping will be reformatted withjoin_key_value()using the given separator andensure_asciisetting. All key-value pairs are output in the order they were defined, with new keys added to the end.Changed in version 0.8.0:
ensure_asciiparameter addedNote
Serializing a
PropertiesFileinstance with thedump()function instead will cause all formatting information to be ignored, asdump()will treat the instance like a normal mapping.- Parameters:
fp (TextIO) – A file-like object to write the mapping to. It must have been opened as a text file with a Latin-1-compatible encoding.
separator (str) – The string to use for separating new or modified keys & values. Only
" ","=", and":"(possibly with added whitespace) should ever be used as the separator.ensure_ascii (bool) – if true, all non-ASCII characters in new or modified key-value pairs will be replaced with
\uXXXXescape sequences in the output; if false, non-ASCII characters will be passed through as-is
- Returns:
- dumps(separator: str = '=', ensure_ascii: bool = True) str[source]
Convert the mapping to a
strin simple line-oriented.propertiesformat.If the instance was originally created from a file or string with
PropertiesFile.load()orPropertiesFile.loads(), then the output will include the comments and whitespace from the original input, and any keys that haven’t been deleted or reassigned will retain their original formatting and multiplicity. Key-value pairs that have been modified or added to the mapping will be reformatted withjoin_key_value()using the given separator andensure_asciisetting. All key-value pairs are output in the order they were defined, with new keys added to the end.Changed in version 0.8.0:
ensure_asciiparameter addedNote
Serializing a
PropertiesFileinstance with thedumps()function instead will cause all formatting information to be ignored, asdumps()will treat the instance like a normal mapping.- Parameters:
separator (str) – The string to use for separating new or modified keys & values. Only
" ","=", and":"(possibly with added whitespace) should ever be used as the separator.ensure_ascii (bool) – if true, all non-ASCII characters in new or modified key-value pairs will be replaced with
\uXXXXescape sequences in the output; if false, non-ASCII characters will be passed through as-is
- Return type:
- property header_comment: str | None
Added in version 0.7.0.
The concatenated values of all comments at the top of the file, up to (but not including) the first key-value pair or timestamp comment, whichever comes first. The comments are returned with comment markers and the whitespace leading up to them removed, with line endings changed to
\n, and with the line ending on the final comment (if any) removed. Blank/all-whitespace lines among the comments are ignored.The header comment can be changed by assigning to this property. Assigning a string
scauses everything before the first key-value pair or timestamp comment to be replaced by the output ofto_comment(s). AssigningNonecauses the header comment to be deleted (also achievable withdel pf.header_comment).>>> pf = PropertiesFile.loads('''\ ... #This is a comment. ... ! This is also a comment. ... #Tue Feb 25 19:13:27 EST 2020 ... key = value ... zebra: apple ... ''') >>> pf.header_comment 'This is a comment.\n This is also a comment.' >>> pf.header_comment = 'New comment' >>> print(pf.dumps(), end='') #New comment #Tue Feb 25 19:13:27 EST 2020 key = value zebra: apple >>> del pf.header_comment >>> pf.header_comment is None True >>> print(pf.dumps(), end='') #Tue Feb 25 19:13:27 EST 2020 key = value zebra: apple
- classmethod load(fp: IO) PropertiesFile[source]
Parse the contents of the
readline-supporting file-like objectfpas a simple line-oriented.propertiesfile and return aPropertiesFileinstance.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.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
.propertiesdocument- Return type:
- Raises:
InvalidUEscapeError – if an invalid
\uXXXXescape sequence occurs in the input
- classmethod loads(s: AnyStr) PropertiesFile[source]
Parse the contents of the string
sas a simple line-oriented.propertiesfile and return aPropertiesFileinstance.smay be either a text string or bytes string. If it is a bytes string, its contents are decoded as Latin-1.Changed in version 0.5.0: Invalid
\uXXXXescape sequences will now cause anInvalidUEscapeErrorto be raised- Parameters:
s (Union[str,bytes]) – the string from which to read the
.propertiesdocument- Return type:
- Raises:
InvalidUEscapeError – if an invalid
\uXXXXescape sequence occurs in the input
- property timestamp: str | None
Added in version 0.7.0.
The value of the timestamp comment, with the comment marker, any whitespace leading up to it, and the trailing newline removed. The timestamp comment is the first comment that appears to be a valid timestamp as produced by Java 8’s
Date.toString()and that does not come after any key-value pairs; if there is no such comment, the value of this property isNone.The timestamp can be changed by assigning to this property. Assigning a string
sreplaces the timestamp comment with the output ofto_comment(s); no check is made as to whether the result is a valid timestamp comment. AssigningNoneorFalsecauses the timestamp comment to be deleted (also achievable withdel pf.timestamp). Assigning any other valuexreplaces the timestamp comment with the output ofto_comment(java_timestamp(x)).>>> pf = PropertiesFile.loads('''\ ... #This is a comment. ... #Tue Feb 25 19:13:27 EST 2020 ... key = value ... zebra: apple ... ''') >>> pf.timestamp 'Tue Feb 25 19:13:27 EST 2020' >>> pf.timestamp = 1234567890 >>> pf.timestamp 'Fri Feb 13 18:31:30 EST 2009' >>> print(pf.dumps(), end='') #This is a comment. #Fri Feb 13 18:31:30 EST 2009 key = value zebra: apple >>> del pf.timestamp >>> pf.timestamp is None True >>> print(pf.dumps(), end='') #This is a comment. key = value zebra: apple