file will not be closed when the :class:`LZMAFile` is closed.
The *mode* argument can be either ``"r"`` for reading (default), ``"w"`` for
- overwriting, or ``"a"`` for appending. If *filename* is an existing file
- object, a mode of ``"w"`` does not truncate the file, and is instead
- equivalent to ``"a"``.
+ overwriting, or ``"a"`` for appending. These can equivalently be given as
+ ``"rb"``, ``"wb"``, and ``"ab"`` respectively.
+
+ If *filename* is a file object (rather than an actual file name), a mode of
+ ``"w"`` does not truncate the file, and is instead equivalent to ``"a"``.
When opening a file for reading, the input file may be the concatenation of
multiple separate compressed streams. These are transparently decoded as a
be an existing file object to read from or write to.
mode can be "r" for reading (default), "w" for (over)writing, or
- "a" for appending.
+ "a" for appending. These can equivalently be given as "rb", "wb",
+ and "ab" respectively.
format specifies the container format to use for the file.
If mode is "r", this defaults to FORMAT_AUTO. Otherwise, the
self._pos = 0
self._size = -1
- if mode == "r":
+ if mode in ("r", "rb"):
if check != -1:
raise ValueError("Cannot specify an integrity check "
"when opening a file for reading")
self._init_args = {"format":format, "filters":filters}
self._decompressor = LZMADecompressor(**self._init_args)
self._buffer = None
- elif mode in ("w", "a"):
+ elif mode in ("w", "wb", "a", "ab"):
if format is None:
format = FORMAT_XZ
mode_code = _MODE_WRITE
raise ValueError("Invalid mode: {!r}".format(mode))
if isinstance(filename, (str, bytes)):
- mode += "b"
+ if "b" not in mode:
+ mode += "b"
self._fp = open(filename, mode)
self._closefp = True
self._mode = mode_code
with LZMAFile(TESTFN, "a") as f:
pass
+ def test_init_mode(self):
+ with TempFile(TESTFN):
+ with LZMAFile(TESTFN, "r"):
+ pass
+ with LZMAFile(TESTFN, "rb"):
+ pass
+ with LZMAFile(TESTFN, "w"):
+ pass
+ with LZMAFile(TESTFN, "wb"):
+ pass
+ with LZMAFile(TESTFN, "a"):
+ pass
+ with LZMAFile(TESTFN, "ab"):
+ pass
+
def test_init_bad_mode(self):
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), (3, "x"))
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "x")
with self.assertRaises(ValueError):
- LZMAFile(BytesIO(COMPRESSED_XZ), "rb")
+ LZMAFile(BytesIO(COMPRESSED_XZ), "rt")
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "r+")
with self.assertRaises(ValueError):
- LZMAFile(BytesIO(COMPRESSED_XZ), "wb")
+ LZMAFile(BytesIO(COMPRESSED_XZ), "wt")
with self.assertRaises(ValueError):
LZMAFile(BytesIO(COMPRESSED_XZ), "w+")
with self.assertRaises(ValueError):
Library
-------
+- LZMAFile now accepts the modes "rb"/"wb"/"ab" as synonyms of "r"/"w"/"a".
+
- The bz2 module now contains an open() function, allowing compressed files to
conveniently be opened in text mode as well as binary mode.