bz2.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. """Interface to the libbzip2 compression library.
  2. This module provides a file interface, classes for incremental
  3. (de)compression, and functions for one-shot (de)compression.
  4. """
  5. __all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor",
  6. "open", "compress", "decompress"]
  7. __author__ = "Nadeem Vawda <nadeem.vawda@gmail.com>"
  8. from builtins import open as _builtin_open
  9. import io
  10. import os
  11. import _compression
  12. from _bz2 import BZ2Compressor, BZ2Decompressor
  13. _MODE_CLOSED = 0
  14. _MODE_READ = 1
  15. # Value 2 no longer used
  16. _MODE_WRITE = 3
  17. class BZ2File(_compression.BaseStream):
  18. """A file object providing transparent bzip2 (de)compression.
  19. A BZ2File can act as a wrapper for an existing file object, or refer
  20. directly to a named file on disk.
  21. Note that BZ2File provides a *binary* file interface - data read is
  22. returned as bytes, and data to be written should be given as bytes.
  23. """
  24. def __init__(self, filename, mode="r", *, compresslevel=9):
  25. """Open a bzip2-compressed file.
  26. If filename is a str, bytes, or PathLike object, it gives the
  27. name of the file to be opened. Otherwise, it should be a file
  28. object, which will be used to read or write the compressed data.
  29. mode can be 'r' for reading (default), 'w' for (over)writing,
  30. 'x' for creating exclusively, or 'a' for appending. These can
  31. equivalently be given as 'rb', 'wb', 'xb', and 'ab'.
  32. If mode is 'w', 'x' or 'a', compresslevel can be a number between 1
  33. and 9 specifying the level of compression: 1 produces the least
  34. compression, and 9 (default) produces the most compression.
  35. If mode is 'r', the input file may be the concatenation of
  36. multiple compressed streams.
  37. """
  38. self._fp = None
  39. self._closefp = False
  40. self._mode = _MODE_CLOSED
  41. if not (1 <= compresslevel <= 9):
  42. raise ValueError("compresslevel must be between 1 and 9")
  43. if mode in ("", "r", "rb"):
  44. mode = "rb"
  45. mode_code = _MODE_READ
  46. elif mode in ("w", "wb"):
  47. mode = "wb"
  48. mode_code = _MODE_WRITE
  49. self._compressor = BZ2Compressor(compresslevel)
  50. elif mode in ("x", "xb"):
  51. mode = "xb"
  52. mode_code = _MODE_WRITE
  53. self._compressor = BZ2Compressor(compresslevel)
  54. elif mode in ("a", "ab"):
  55. mode = "ab"
  56. mode_code = _MODE_WRITE
  57. self._compressor = BZ2Compressor(compresslevel)
  58. else:
  59. raise ValueError("Invalid mode: %r" % (mode,))
  60. if isinstance(filename, (str, bytes, os.PathLike)):
  61. self._fp = _builtin_open(filename, mode)
  62. self._closefp = True
  63. self._mode = mode_code
  64. elif hasattr(filename, "read") or hasattr(filename, "write"):
  65. self._fp = filename
  66. self._mode = mode_code
  67. else:
  68. raise TypeError("filename must be a str, bytes, file or PathLike object")
  69. if self._mode == _MODE_READ:
  70. raw = _compression.DecompressReader(self._fp,
  71. BZ2Decompressor, trailing_error=OSError)
  72. self._buffer = io.BufferedReader(raw)
  73. else:
  74. self._pos = 0
  75. def close(self):
  76. """Flush and close the file.
  77. May be called more than once without error. Once the file is
  78. closed, any other operation on it will raise a ValueError.
  79. """
  80. if self._mode == _MODE_CLOSED:
  81. return
  82. try:
  83. if self._mode == _MODE_READ:
  84. self._buffer.close()
  85. elif self._mode == _MODE_WRITE:
  86. self._fp.write(self._compressor.flush())
  87. self._compressor = None
  88. finally:
  89. try:
  90. if self._closefp:
  91. self._fp.close()
  92. finally:
  93. self._fp = None
  94. self._closefp = False
  95. self._mode = _MODE_CLOSED
  96. self._buffer = None
  97. @property
  98. def closed(self):
  99. """True if this file is closed."""
  100. return self._mode == _MODE_CLOSED
  101. def fileno(self):
  102. """Return the file descriptor for the underlying file."""
  103. self._check_not_closed()
  104. return self._fp.fileno()
  105. def seekable(self):
  106. """Return whether the file supports seeking."""
  107. return self.readable() and self._buffer.seekable()
  108. def readable(self):
  109. """Return whether the file was opened for reading."""
  110. self._check_not_closed()
  111. return self._mode == _MODE_READ
  112. def writable(self):
  113. """Return whether the file was opened for writing."""
  114. self._check_not_closed()
  115. return self._mode == _MODE_WRITE
  116. def peek(self, n=0):
  117. """Return buffered data without advancing the file position.
  118. Always returns at least one byte of data, unless at EOF.
  119. The exact number of bytes returned is unspecified.
  120. """
  121. self._check_can_read()
  122. # Relies on the undocumented fact that BufferedReader.peek()
  123. # always returns at least one byte (except at EOF), independent
  124. # of the value of n
  125. return self._buffer.peek(n)
  126. def read(self, size=-1):
  127. """Read up to size uncompressed bytes from the file.
  128. If size is negative or omitted, read until EOF is reached.
  129. Returns b'' if the file is already at EOF.
  130. """
  131. self._check_can_read()
  132. return self._buffer.read(size)
  133. def read1(self, size=-1):
  134. """Read up to size uncompressed bytes, while trying to avoid
  135. making multiple reads from the underlying stream. Reads up to a
  136. buffer's worth of data if size is negative.
  137. Returns b'' if the file is at EOF.
  138. """
  139. self._check_can_read()
  140. if size < 0:
  141. size = io.DEFAULT_BUFFER_SIZE
  142. return self._buffer.read1(size)
  143. def readinto(self, b):
  144. """Read bytes into b.
  145. Returns the number of bytes read (0 for EOF).
  146. """
  147. self._check_can_read()
  148. return self._buffer.readinto(b)
  149. def readline(self, size=-1):
  150. """Read a line of uncompressed bytes from the file.
  151. The terminating newline (if present) is retained. If size is
  152. non-negative, no more than size bytes will be read (in which
  153. case the line may be incomplete). Returns b'' if already at EOF.
  154. """
  155. if not isinstance(size, int):
  156. if not hasattr(size, "__index__"):
  157. raise TypeError("Integer argument expected")
  158. size = size.__index__()
  159. self._check_can_read()
  160. return self._buffer.readline(size)
  161. def readlines(self, size=-1):
  162. """Read a list of lines of uncompressed bytes from the file.
  163. size can be specified to control the number of lines read: no
  164. further lines will be read once the total size of the lines read
  165. so far equals or exceeds size.
  166. """
  167. if not isinstance(size, int):
  168. if not hasattr(size, "__index__"):
  169. raise TypeError("Integer argument expected")
  170. size = size.__index__()
  171. self._check_can_read()
  172. return self._buffer.readlines(size)
  173. def write(self, data):
  174. """Write a byte string to the file.
  175. Returns the number of uncompressed bytes written, which is
  176. always the length of data in bytes. Note that due to buffering,
  177. the file on disk may not reflect the data written until close()
  178. is called.
  179. """
  180. self._check_can_write()
  181. if isinstance(data, (bytes, bytearray)):
  182. length = len(data)
  183. else:
  184. # accept any data that supports the buffer protocol
  185. data = memoryview(data)
  186. length = data.nbytes
  187. compressed = self._compressor.compress(data)
  188. self._fp.write(compressed)
  189. self._pos += length
  190. return length
  191. def writelines(self, seq):
  192. """Write a sequence of byte strings to the file.
  193. Returns the number of uncompressed bytes written.
  194. seq can be any iterable yielding byte strings.
  195. Line separators are not added between the written byte strings.
  196. """
  197. return _compression.BaseStream.writelines(self, seq)
  198. def seek(self, offset, whence=io.SEEK_SET):
  199. """Change the file position.
  200. The new position is specified by offset, relative to the
  201. position indicated by whence. Values for whence are:
  202. 0: start of stream (default); offset must not be negative
  203. 1: current stream position
  204. 2: end of stream; offset must not be positive
  205. Returns the new file position.
  206. Note that seeking is emulated, so depending on the parameters,
  207. this operation may be extremely slow.
  208. """
  209. self._check_can_seek()
  210. return self._buffer.seek(offset, whence)
  211. def tell(self):
  212. """Return the current file position."""
  213. self._check_not_closed()
  214. if self._mode == _MODE_READ:
  215. return self._buffer.tell()
  216. return self._pos
  217. def open(filename, mode="rb", compresslevel=9,
  218. encoding=None, errors=None, newline=None):
  219. """Open a bzip2-compressed file in binary or text mode.
  220. The filename argument can be an actual filename (a str, bytes, or
  221. PathLike object), or an existing file object to read from or write
  222. to.
  223. The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or
  224. "ab" for binary mode, or "rt", "wt", "xt" or "at" for text mode.
  225. The default mode is "rb", and the default compresslevel is 9.
  226. For binary mode, this function is equivalent to the BZ2File
  227. constructor: BZ2File(filename, mode, compresslevel). In this case,
  228. the encoding, errors and newline arguments must not be provided.
  229. For text mode, a BZ2File object is created, and wrapped in an
  230. io.TextIOWrapper instance with the specified encoding, error
  231. handling behavior, and line ending(s).
  232. """
  233. if "t" in mode:
  234. if "b" in mode:
  235. raise ValueError("Invalid mode: %r" % (mode,))
  236. else:
  237. if encoding is not None:
  238. raise ValueError("Argument 'encoding' not supported in binary mode")
  239. if errors is not None:
  240. raise ValueError("Argument 'errors' not supported in binary mode")
  241. if newline is not None:
  242. raise ValueError("Argument 'newline' not supported in binary mode")
  243. bz_mode = mode.replace("t", "")
  244. binary_file = BZ2File(filename, bz_mode, compresslevel=compresslevel)
  245. if "t" in mode:
  246. encoding = io.text_encoding(encoding)
  247. return io.TextIOWrapper(binary_file, encoding, errors, newline)
  248. else:
  249. return binary_file
  250. def compress(data, compresslevel=9):
  251. """Compress a block of data.
  252. compresslevel, if given, must be a number between 1 and 9.
  253. For incremental compression, use a BZ2Compressor object instead.
  254. """
  255. comp = BZ2Compressor(compresslevel)
  256. return comp.compress(data) + comp.flush()
  257. def decompress(data):
  258. """Decompress a block of data.
  259. For incremental decompression, use a BZ2Decompressor object instead.
  260. """
  261. results = []
  262. while data:
  263. decomp = BZ2Decompressor()
  264. try:
  265. res = decomp.decompress(data)
  266. except OSError:
  267. if results:
  268. break # Leftover data is not a valid bzip2 stream; ignore it.
  269. else:
  270. raise # Error on the first iteration; bail out.
  271. results.append(res)
  272. if not decomp.eof:
  273. raise ValueError("Compressed data ended before the "
  274. "end-of-stream marker was reached")
  275. data = decomp.unused_data
  276. return b"".join(results)