Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit af518c1

Browse files
committed
Add a function bz2.open(), to match gzip.open().
1 parent 50cb936 commit af518c1

4 files changed

Lines changed: 184 additions & 16 deletions

File tree

Doc/library/bz2.rst

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ decompressing data using the bzip2 compression algorithm.
1414

1515
The :mod:`bz2` module contains:
1616

17-
* The :class:`BZ2File` class for reading and writing compressed files.
17+
* The :func:`.open` function and :class:`BZ2File` class for reading and
18+
writing compressed files.
1819
* The :class:`BZ2Compressor` and :class:`BZ2Decompressor` classes for
1920
incremental (de)compression.
2021
* The :func:`compress` and :func:`decompress` functions for one-shot
@@ -26,9 +27,37 @@ All of the classes in this module may safely be accessed from multiple threads.
2627
(De)compression of files
2728
------------------------
2829

30+
.. function:: open(filename, mode='r', compresslevel=9, encoding=None, errors=None, newline=None)
31+
32+
Open a bzip2-compressed file in binary or text mode, returning a :term:`file
33+
object`.
34+
35+
As with the constructor for :class:`BZ2File`, the *filename* argument can be
36+
an actual filename (a :class:`str` or :class:`bytes` object), or an existing
37+
file object to read from or write to.
38+
39+
The *mode* argument can be any of ``'r'``, ``'rb'``, ``'w'``, ``'wb'``,
40+
``'a'``, or ``'ab'`` for binary mode, or ``'rt'``, ``'wt'``, or ``'at'`` for
41+
text mode. The default is ``'rb'``.
42+
43+
The *compresslevel* argument is an integer from 1 to 9, as for the
44+
:class:`BZ2File` constructor.
45+
46+
For binary mode, this function is equivalent to the :class:`BZ2File`
47+
constructor: ``BZ2File(filename, mode, compresslevel=compresslevel)``. In
48+
this case, the *encoding*, *errors* and *newline* arguments must not be
49+
provided.
50+
51+
For text mode, a :class:`BZ2File` object is created, and wrapped in an
52+
:class:`io.TextIOWrapper` instance with the specified encoding, error
53+
handling behavior, and line ending(s).
54+
55+
.. versionadded:: 3.3
56+
57+
2958
.. class:: BZ2File(filename, mode='r', buffering=None, compresslevel=9)
3059

31-
Open a bzip2-compressed file.
60+
Open a bzip2-compressed file in binary mode.
3261

3362
If *filename* is a :class:`str` or :class:`bytes` object, open the named file
3463
directly. Otherwise, *filename* should be a :term:`file object`, which will

Lib/bz2.py

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,12 @@
44
(de)compression, and functions for one-shot (de)compression.
55
"""
66

7-
__all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor", "compress",
8-
"decompress"]
7+
__all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor",
8+
"open", "compress", "decompress"]
99

1010
__author__ = "Nadeem Vawda <[email protected]>"
1111

12+
import builtins
1213
import io
1314
import warnings
1415

@@ -91,7 +92,7 @@ def __init__(self, filename, mode="r", buffering=None, compresslevel=9):
9192
raise ValueError("Invalid mode: {!r}".format(mode))
9293

9394
if isinstance(filename, (str, bytes)):
94-
self._fp = open(filename, mode)
95+
self._fp = builtins.open(filename, mode)
9596
self._closefp = True
9697
self._mode = mode_code
9798
elif hasattr(filename, "read") or hasattr(filename, "write"):
@@ -391,6 +392,46 @@ def tell(self):
391392
return self._pos
392393

393394

395+
def open(filename, mode="rb", compresslevel=9,
396+
encoding=None, errors=None, newline=None):
397+
"""Open a bzip2-compressed file in binary or text mode.
398+
399+
The filename argument can be an actual filename (a str or bytes object), or
400+
an existing file object to read from or write to.
401+
402+
The mode argument can be "r", "rb", "w", "wb", "a" or "ab" for binary mode,
403+
or "rt", "wt" or "at" for text mode. The default mode is "rb", and the
404+
default compresslevel is 9.
405+
406+
For binary mode, this function is equivalent to the BZ2File constructor:
407+
BZ2File(filename, mode, compresslevel). In this case, the encoding, errors
408+
and newline arguments must not be provided.
409+
410+
For text mode, a BZ2File object is created, and wrapped in an
411+
io.TextIOWrapper instance with the specified encoding, error handling
412+
behavior, and line ending(s).
413+
414+
"""
415+
if "t" in mode:
416+
if "b" in mode:
417+
raise ValueError("Invalid mode: %r" % (mode,))
418+
else:
419+
if encoding is not None:
420+
raise ValueError("Argument 'encoding' not supported in binary mode")
421+
if errors is not None:
422+
raise ValueError("Argument 'errors' not supported in binary mode")
423+
if newline is not None:
424+
raise ValueError("Argument 'newline' not supported in binary mode")
425+
426+
bz_mode = mode.replace("t", "")
427+
binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel)
428+
429+
if "t" in mode:
430+
return io.TextIOWrapper(binary_file, encoding, errors, newline)
431+
else:
432+
return binary_file
433+
434+
394435
def compress(data, compresslevel=9):
395436
"""Compress a block of data.
396437

Lib/test/test_bz2.py

Lines changed: 106 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,13 @@ class BaseTest(unittest.TestCase):
4848
TEXT = b''.join(TEXT_LINES)
4949
DATA = b'BZh91AY&SY.\xc8N\x18\x00\x01>_\x80\x00\x10@\x02\xff\xf0\x01\x07n\x00?\xe7\xff\xe00\x01\x99\xaa\x00\xc0\x03F\x86\x8c#&\x83F\x9a\x03\x06\xa6\xd0\xa6\x93M\x0fQ\xa7\xa8\x06\x804hh\x12$\x11\xa4i4\xf14S\xd2<Q\xb5\x0fH\xd3\xd4\xdd\xd5\x87\xbb\xf8\x94\r\x8f\xafI\x12\xe1\xc9\xf8/E\x00pu\x89\x12]\xc9\xbbDL\nQ\x0e\t1\x12\xdf\xa0\xc0\x97\xac2O9\x89\x13\x94\x0e\x1c7\x0ed\x95I\x0c\xaaJ\xa4\x18L\x10\x05#\x9c\xaf\xba\xbc/\x97\x8a#C\xc8\xe1\x8cW\xf9\xe2\xd0\xd6M\xa7\x8bXa<e\x84t\xcbL\xb3\xa7\xd9\xcd\xd1\xcb\x84.\xaf\xb3\xab\xab\xad`n}\xa0lh\tE,\x8eZ\x15\x17VH>\x88\xe5\xcd9gd6\x0b\n\xe9\x9b\xd5\x8a\x99\xf7\x08.K\x8ev\xfb\xf7xw\xbb\xdf\xa1\x92\xf1\xdd|/";\xa2\xba\x9f\xd5\xb1#A\xb6\xf6\xb3o\xc9\xc5y\\\xebO\xe7\x85\x9a\xbc\xb6f8\x952\xd5\xd7"%\x89>V,\xf7\xa6z\xe2\x9f\xa3\xdf\x11\x11"\xd6E)I\xa9\x13^\xca\xf3r\xd0\x03U\x922\xf26\xec\xb6\xed\x8b\xc3U\x13\x9d\xc5\x170\xa4\xfa^\x92\xacDF\x8a\x97\xd6\x19\xfe\xdd\xb8\xbd\x1a\x9a\x19\xa3\x80ankR\x8b\xe5\xd83]\xa9\xc6\x08\x82f\xf6\xb9"6l$\xb8j@\xc0\x8a\xb0l1..\xbak\x83ls\x15\xbc\xf4\xc1\x13\xbe\xf8E\xb8\x9d\r\xa8\x9dk\x84\xd3n\xfa\xacQ\x07\xb1%y\xaav\xb4\x08\xe0z\x1b\x16\xf5\x04\xe9\xcc\xb9\x08z\x1en7.G\xfc]\xc9\x14\xe1B@\xbb!8`'
5050

51+
def setUp(self):
52+
self.filename = TESTFN
53+
54+
def tearDown(self):
55+
if os.path.isfile(self.filename):
56+
os.unlink(self.filename)
57+
5158
if has_cmdline_bunzip2:
5259
def decompress(self, data):
5360
pop = subprocess.Popen("bunzip2", shell=True,
@@ -70,13 +77,6 @@ def decompress(self, data):
7077
class BZ2FileTest(BaseTest):
7178
"Test BZ2File type miscellaneous methods."
7279

73-
def setUp(self):
74-
self.filename = TESTFN
75-
76-
def tearDown(self):
77-
if os.path.isfile(self.filename):
78-
os.unlink(self.filename)
79-
8080
def createTempFile(self, streams=1):
8181
with open(self.filename, "wb") as f:
8282
f.write(self.DATA * streams)
@@ -650,9 +650,7 @@ def testDecompress4G(self, size):
650650
decompressed = None
651651

652652

653-
class FuncTest(BaseTest):
654-
"Test module functions"
655-
653+
class CompressDecompressTest(BaseTest):
656654
def testCompress(self):
657655
data = bz2.compress(self.TEXT)
658656
self.assertEqual(self.decompress(data), self.TEXT)
@@ -672,12 +670,109 @@ def testDecompressMultiStream(self):
672670
text = bz2.decompress(self.DATA * 5)
673671
self.assertEqual(text, self.TEXT * 5)
674672

673+
674+
class OpenTest(BaseTest):
675+
def test_binary_modes(self):
676+
with bz2.open(self.filename, "wb") as f:
677+
f.write(self.TEXT)
678+
with open(self.filename, "rb") as f:
679+
file_data = bz2.decompress(f.read())
680+
self.assertEqual(file_data, self.TEXT)
681+
with bz2.open(self.filename, "rb") as f:
682+
self.assertEqual(f.read(), self.TEXT)
683+
with bz2.open(self.filename, "ab") as f:
684+
f.write(self.TEXT)
685+
with open(self.filename, "rb") as f:
686+
file_data = bz2.decompress(f.read())
687+
self.assertEqual(file_data, self.TEXT * 2)
688+
689+
def test_implicit_binary_modes(self):
690+
# Test implicit binary modes (no "b" or "t" in mode string).
691+
with bz2.open(self.filename, "w") as f:
692+
f.write(self.TEXT)
693+
with open(self.filename, "rb") as f:
694+
file_data = bz2.decompress(f.read())
695+
self.assertEqual(file_data, self.TEXT)
696+
with bz2.open(self.filename, "r") as f:
697+
self.assertEqual(f.read(), self.TEXT)
698+
with bz2.open(self.filename, "a") as f:
699+
f.write(self.TEXT)
700+
with open(self.filename, "rb") as f:
701+
file_data = bz2.decompress(f.read())
702+
self.assertEqual(file_data, self.TEXT * 2)
703+
704+
def test_text_modes(self):
705+
text = self.TEXT.decode("ascii")
706+
text_native_eol = text.replace("\n", os.linesep)
707+
with bz2.open(self.filename, "wt") as f:
708+
f.write(text)
709+
with open(self.filename, "rb") as f:
710+
file_data = bz2.decompress(f.read()).decode("ascii")
711+
self.assertEqual(file_data, text_native_eol)
712+
with bz2.open(self.filename, "rt") as f:
713+
self.assertEqual(f.read(), text)
714+
with bz2.open(self.filename, "at") as f:
715+
f.write(text)
716+
with open(self.filename, "rb") as f:
717+
file_data = bz2.decompress(f.read()).decode("ascii")
718+
self.assertEqual(file_data, text_native_eol * 2)
719+
720+
def test_fileobj(self):
721+
with bz2.open(BytesIO(self.DATA), "r") as f:
722+
self.assertEqual(f.read(), self.TEXT)
723+
with bz2.open(BytesIO(self.DATA), "rb") as f:
724+
self.assertEqual(f.read(), self.TEXT)
725+
text = self.TEXT.decode("ascii")
726+
with bz2.open(BytesIO(self.DATA), "rt") as f:
727+
self.assertEqual(f.read(), text)
728+
729+
def test_bad_params(self):
730+
# Test invalid parameter combinations.
731+
with self.assertRaises(ValueError):
732+
bz2.open(self.filename, "wbt")
733+
with self.assertRaises(ValueError):
734+
bz2.open(self.filename, "rb", encoding="utf-8")
735+
with self.assertRaises(ValueError):
736+
bz2.open(self.filename, "rb", errors="ignore")
737+
with self.assertRaises(ValueError):
738+
bz2.open(self.filename, "rb", newline="\n")
739+
740+
def test_encoding(self):
741+
# Test non-default encoding.
742+
text = self.TEXT.decode("ascii")
743+
text_native_eol = text.replace("\n", os.linesep)
744+
with bz2.open(self.filename, "wt", encoding="utf-16-le") as f:
745+
f.write(text)
746+
with open(self.filename, "rb") as f:
747+
file_data = bz2.decompress(f.read()).decode("utf-16-le")
748+
self.assertEqual(file_data, text_native_eol)
749+
with bz2.open(self.filename, "rt", encoding="utf-16-le") as f:
750+
self.assertEqual(f.read(), text)
751+
752+
def test_encoding_error_handler(self):
753+
# Test with non-default encoding error handler.
754+
with bz2.open(self.filename, "wb") as f:
755+
f.write(b"foo\xffbar")
756+
with bz2.open(self.filename, "rt", encoding="ascii", errors="ignore") \
757+
as f:
758+
self.assertEqual(f.read(), "foobar")
759+
760+
def test_newline(self):
761+
# Test with explicit newline (universal newline mode disabled).
762+
text = self.TEXT.decode("ascii")
763+
with bz2.open(self.filename, "wt", newline="\n") as f:
764+
f.write(text)
765+
with bz2.open(self.filename, "rt", newline="\r") as f:
766+
self.assertEqual(f.readlines(), [text])
767+
768+
675769
def test_main():
676770
support.run_unittest(
677771
BZ2FileTest,
678772
BZ2CompressorTest,
679773
BZ2DecompressorTest,
680-
FuncTest
774+
CompressDecompressTest,
775+
OpenTest,
681776
)
682777
support.reap_children()
683778

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ Core and Builtins
1515
Library
1616
-------
1717

18+
- The bz2 module now contains an open() function, allowing compressed files to
19+
conveniently be opened in text mode as well as binary mode.
20+
1821
- BZ2File.__init__() now accepts a file object as its first argument, rather
1922
than requiring a separate "fileobj" argument.
2023

0 commit comments

Comments
 (0)