“Python/docs/3.9/library/bz2”的版本间差异

来自菜鸟教程
Python/docs/3.9/library/bz2
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:bz2 — 支持 bzip2 压缩 — Python 文档}}
 
<div id="module-bz2" class="section">
 
<div id="module-bz2" class="section">
  
 
<span id="bz2-support-for-bzip2-compression"></span>
 
<span id="bz2-support-for-bzip2-compression"></span>
= [[#module-bz2|<code>bz2</code>]] --- Support for '''bzip2''' compression =
+
= bz2 — 支持 bzip2 压缩 =
  
'''Source code:''' [https://github.com/python/cpython/tree/3.9/Lib/bz2.py Lib/bz2.py]
+
'''源代码:''' [[#id1|<span id="id2" class="problematic">:source:`Lib/bz2.py`</span>]]
  
This module provides a comprehensive interface for compressing and
 
decompressing data using the bzip2 compression algorithm.
 
  
The [[#module-bz2|<code>bz2</code>]] module contains:
+
-----
  
* The [[#bz2.open|<code>open()</code>]] function and [[#bz2.BZ2File|<code>BZ2File</code>]] class for reading and writing compressed files.
+
该模块提供了一个使用 bzip2 压缩算法压缩和解压缩数据的综合接口。
* The [[#bz2.BZ2Compressor|<code>BZ2Compressor</code>]] and [[#bz2.BZ2Decompressor|<code>BZ2Decompressor</code>]] classes for incremental (de)compression.
 
* The [[#bz2.compress|<code>compress()</code>]] and [[#bz2.decompress|<code>decompress()</code>]] functions for one-shot (de)compression.
 
  
All of the classes in this module may safely be accessed from multiple threads.
+
[[#module-bz2|bz2]] 模块包含:
 +
 
 +
* [[#bz2.open|open()]] 函数和 [[#bz2.BZ2File|BZ2File]] 类用于读取和写入压缩文件。
 +
* 用于增量(解)压缩的 [[#bz2.BZ2Compressor|BZ2Compressor]] 和 [[#bz2.BZ2Decompressor|BZ2Decompressor]] 类。
 +
* [[#bz2.compress|compress()]] 和 [[#bz2.decompress|decompress()]] 函数用于一次性(解)压缩。
 +
 
 +
该模块中的所有类都可以安全地从多个线程访问。
  
 
<div id="de-compression-of-files" class="section">
 
<div id="de-compression-of-files" class="section">
  
== (De)compression of files ==
+
== ()压缩文件 ==
  
 
<dl>
 
<dl>
<dt><code>bz2.</code><code>open</code><span class="sig-paren">(</span>''<span class="n">filename</span>'', ''<span class="n">mode</span><span class="o">=</span><span class="default_value">'rb'</span>'', ''<span class="n">compresslevel</span><span class="o">=</span><span class="default_value">9</span>'', ''<span class="n">encoding</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">errors</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">newline</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">bz2.</span></span><span class="sig-name descname"><span class="pre">open</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">filename</span></span>'', ''<span class="n"><span class="pre">mode</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'rb'</span></span>'', ''<span class="n"><span class="pre">compresslevel</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">9</span></span>'', ''<span class="n"><span class="pre">encoding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">errors</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">newline</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Open a bzip2-compressed file in binary or text mode, returning a [[../../glossary#term-file-object|<span class="xref std std-term">file
+
<dd><p>以二进制或文本模式打开 bzip2 压缩文件,返回 [[../../glossary#term-file-object|文件对象]] </p>
object</span>]].</p>
+
<p>[[#bz2.BZ2File|BZ2File]] 的构造函数一样,''filename'' 参数可以是实际的文件名([[../stdtypes#str|str]] [[../stdtypes#bytes|bytes]] 对象),也可以是现有的要读取或写入的文件对象。</p>
<p>As with the constructor for [[#bz2.BZ2File|<code>BZ2File</code>]], the ''filename'' argument can be
+
<p>''mode'' 参数可以是 <code>'r'</code><code>'rb'</code><code>'w'</code><code>'wb'</code><code>'x'</code><code>'xb'</code><code>'a'</code> <code>'ab'</code> 用于二进制模式,或 <code>'rt'</code><code>'wt'</code><code>'xt'</code> 或 ] 用于文本模式。 默认值为 <code>'rb'</code></p>
an actual filename (a [[../stdtypes#str|<code>str</code>]] or [[../stdtypes#bytes|<code>bytes</code>]] object), or an existing
+
<p>''compresslevel'' 参数是一个从 1 9 的整数,对于 [[#bz2.BZ2File|BZ2File]] 构造函数。</p>
file object to read from or write to.</p>
+
<p>对于二进制模式,此函数等效于 [[#bz2.BZ2File|BZ2File]] 构造函数:<code>BZ2File(filename, mode, compresslevel=compresslevel)</code>。 在这种情况下,不得提供 ''encoding''''errors'' ''newline'' 参数。</p>
<p>The ''mode'' argument can be any of <code>'r'</code>, <code>'rb'</code>, <code>'w'</code>, <code>'wb'</code>,
+
<p>对于文本模式,会创建一个 [[#bz2.BZ2File|BZ2File]] 对象,并将其包装在具有指定编码、错误处理行为和行尾的 [[../io#io|io.TextIOWrapper]] 实例中。</p>
<code>'x'</code>, <code>'xb'</code>, <code>'a'</code> or <code>'ab'</code> for binary mode, or <code>'rt'</code>,
 
<code>'wt'</code>, <code>'xt'</code>, or <code>'at'</code> for text mode. The default is <code>'rb'</code>.</p>
 
<p>The ''compresslevel'' argument is an integer from 1 to 9, as for the
 
[[#bz2.BZ2File|<code>BZ2File</code>]] constructor.</p>
 
<p>For binary mode, this function is equivalent to the [[#bz2.BZ2File|<code>BZ2File</code>]]
 
constructor: <code>BZ2File(filename, mode, compresslevel=compresslevel)</code>. In
 
this case, the ''encoding'', ''errors'' and ''newline'' arguments must not be
 
provided.</p>
 
<p>For text mode, a [[#bz2.BZ2File|<code>BZ2File</code>]] object is created, and wrapped in an
 
[[../io#io|<code>io.TextIOWrapper</code>]] instance with the specified encoding, error
 
handling behavior, and line ending(s).</p>
 
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.3 新版功能.</span></p>
+
<p><span class="versionmodified added">3.3 版中的新功能。</span></p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.4 版更改: </span>The <code>'x'</code> (exclusive creation) mode was added.</p>
+
<p><span class="versionmodified changed">3.4版本变更:</span>增加了<code>'x'</code>(独创)模式。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.6 版更改: </span>Accepts a [[../../glossary#term-path-like-object|<span class="xref std std-term">path-like object</span>]].</p>
+
<p><span class="versionmodified changed"> 3.6 版更改:</span> 接受 [[../../glossary#term-path-like-object|类路径对象]] </p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt>''class'' <code>bz2.</code><code>BZ2File</code><span class="sig-paren">(</span>''<span class="n">filename</span>'', ''<span class="n">mode</span><span class="o">=</span><span class="default_value">'r'</span>'', ''<span class="o">*</span>'', ''<span class="n">compresslevel</span><span class="o">=</span><span class="default_value">9</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">bz2.</span></span><span class="sig-name descname"><span class="pre">BZ2File</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">filename</span></span>'', ''<span class="n"><span class="pre">mode</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'r'</span></span>'', ''<span class="o"><span class="pre">*</span></span>'', ''<span class="n"><span class="pre">compresslevel</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">9</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Open a bzip2-compressed file in binary mode.</p>
+
<dd><p>以二进制模式打开 bzip2 压缩文件。</p>
<p>If ''filename'' is a [[../stdtypes#str|<code>str</code>]] or [[../stdtypes#bytes|<code>bytes</code>]] object, open the named file
+
<p>如果 ''filename'' [[../stdtypes#str|str]] [[../stdtypes#bytes|bytes]] 对象,则直接打开命名文件。 否则,''filename'' 应该是一个 [[../../glossary#term-file-object|file object]],它将用于读取或写入压缩数据。</p>
directly. Otherwise, ''filename'' should be a [[../../glossary#term-file-object|<span class="xref std std-term">file object</span>]], which will
+
<p>''mode'' 参数可以是用于读取的 <code>'r'</code>(默认)、用于覆盖的 <code>'w'</code>、用于独占创建的 <code>'x'</code> <code>'a'</code>用于附加。 这些可以分别等效地表示为 <code>'rb'</code><code>'wb'</code><code>'xb'</code> <code>'ab'</code></p>
be used to read or write the compressed data.</p>
+
<p>如果 ''filename'' 是文件对象(而不是实际文件名),则 <code>'w'</code> 模式不会截断文件,而是等效于 <code>'a'</code></p>
<p>The ''mode'' argument can be either <code>'r'</code> for reading (default), <code>'w'</code> for
+
<p>如果 ''mode'' <code>'w'</code> <code>'a'</code>,则 ''compresslevel'' 可以是 <code>1</code> <code>9</code> 之间的整数,指定压缩级别:<code>1</code> 产生的压缩最少,而 <code>9</code>(默认)产生的压缩最多。</p>
overwriting, <code>'x'</code> for exclusive creation, or <code>'a'</code> for appending. These
+
<p>如果''mode''<code>'r'</code>,则输入文件可能是多个压缩流的串联。</p>
can equivalently be given as <code>'rb'</code>, <code>'wb'</code>, <code>'xb'</code> and <code>'ab'</code>
+
<p>[[#bz2.BZ2File|BZ2File]] 提供了 [[../io#io|io.BufferedIOBase]] 指定的所有成员,除了 <code>detach()</code> <code>truncate()</code>。 支持迭代和 [[../../reference/compound_stmts#with|with]] 语句。</p>
respectively.</p>
+
<p>[[#bz2.BZ2File|BZ2File]] 还提供了如下方法:</p>
<p>If ''filename'' is a file object (rather than an actual file name), a mode of
 
<code>'w'</code> does not truncate the file, and is instead equivalent to <code>'a'</code>.</p>
 
<p>If ''mode'' is <code>'w'</code> or <code>'a'</code>, ''compresslevel'' can be an integer between
 
<code>1</code> and <code>9</code> specifying the level of compression: <code>1</code> produces the
 
least compression, and <code>9</code> (default) produces the most compression.</p>
 
<p>If ''mode'' is <code>'r'</code>, the input file may be the concatenation of multiple
 
compressed streams.</p>
 
<p>[[#bz2.BZ2File|<code>BZ2File</code>]] provides all of the members specified by the
 
[[../io#io|<code>io.BufferedIOBase</code>]], except for <code>detach()</code> and <code>truncate()</code>.
 
Iteration and the [[../../reference/compound_stmts#with|<code>with</code>]] statement are supported.</p>
 
<p>[[#bz2.BZ2File|<code>BZ2File</code>]] also provides the following method:</p>
 
 
<dl>
 
<dl>
<dt><code>peek</code><span class="sig-paren">(</span><span class="optional">[</span>''n''<span class="optional">]</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">peek</span></span><span class="sig-paren">(</span><span class="optional">[</span>''<span class="pre">n</span>''<span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return buffered data without advancing the file position. At least one
+
<dd><p>返回缓冲数据而不推进文件位置。 至少会返回一个字节的数据(除非在 EOF 处)。 返回的确切字节数未指定。</p>
byte of data will be returned (unless at EOF). The exact number of bytes
 
returned is unspecified.</p>
 
 
<div class="admonition note">
 
<div class="admonition note">
  
<p>注解</p>
+
<p>笔记</p>
<p>While calling [[#bz2.BZ2File.peek|<code>peek()</code>]] does not change the file position of
+
<p>虽然调用 [[#bz2.BZ2File.peek|peek()]] 不会改变 [[#bz2.BZ2File|BZ2File]] 的文件位置,但它可能会改变底层文件对象的位置(例如 如果 [[#bz2.BZ2File|BZ2File]] 是通过为 ''filename'' 传递文件对象来构造的)。</p>
the [[#bz2.BZ2File|<code>BZ2File</code>]], it may change the position of the underlying file
 
object (e.g. if the [[#bz2.BZ2File|<code>BZ2File</code>]] was constructed by passing a file
 
object for ''filename'').</p>
 
  
 
</div>
 
</div>
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.3 新版功能.</span></p>
+
<p><span class="versionmodified added">3.3 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
第99行: 第75行:
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.1 版更改: </span>Support for the [[../../reference/compound_stmts#with|<code>with</code>]] statement was added.</p>
+
<p><span class="versionmodified changed"> 3.1 版更改: </span> 添加了对 [[../../reference/compound_stmts#with|with]] 语句的支持。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.3 版更改: </span>The <code>fileno()</code>, <code>readable()</code>, <code>seekable()</code>, <code>writable()</code>,
+
<p><span class="versionmodified changed">3.3 版本变更:</span><code>fileno()</code><code>readable()</code><code>seekable()</code><code>writable()</code><code>read1()</code><code>readinto()</code> 方法。</p>
<code>read1()</code> and <code>readinto()</code> methods were added.</p>
 
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.3 版更改: </span>Support was added for ''filename'' being a [[../../glossary#term-file-object|<span class="xref std std-term">file object</span>]] instead of an
+
<p><span class="versionmodified changed"> 3.3 版更改: </span> 支持 ''文件名'' [[../../glossary#term-file-object|文件对象]] 而不是实际文件名。</p>
actual filename.</p>
 
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.3 版更改: </span>The <code>'a'</code> (append) mode was added, along with support for reading
+
<p><span class="versionmodified changed"> 3.3 版本变更: </span> 添加了 <code>'a'</code>(追加)模式,并支持读取多流文件。</p>
multi-stream files.</p>
 
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.4 版更改: </span>The <code>'x'</code> (exclusive creation) mode was added.</p>
+
<p><span class="versionmodified changed">3.4版本变更:</span>增加了<code>'x'</code>(独创)模式。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.5 版更改: </span>The [[../io#io.BufferedIOBase|<code>read()</code>]] method now accepts an argument of
+
<p><span class="versionmodified changed"> 3.5 版更改: </span> [[../io#io.BufferedIOBase|read()]] 方法现在接受 <code>None</code> 的参数。</p>
<code>None</code>.</p>
 
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.6 版更改: </span>Accepts a [[../../glossary#term-path-like-object|<span class="xref std std-term">path-like object</span>]].</p>
+
<p><span class="versionmodified changed"> 3.6 版更改:</span> 接受 [[../../glossary#term-path-like-object|类路径对象]] </p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.9 版更改: </span>The ''buffering'' parameter has been removed. It was ignored and deprecated
+
<p><span class="versionmodified changed"> 3.9 版更改: </span> 删除了 ''缓冲'' 参数。 自 Python 3.0 以来,它被忽略和弃用。 传递一个打开的文件对象来控制文件的打开方式。</p>
since Python 3.0. Pass an open file object to control how the file is
+
<p>''compresslevel'' 参数变为仅限关键字。</p>
opened.</p>
 
<p>The ''compresslevel'' parameter became keyword-only.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
第149行: 第119行:
 
<div id="incremental-de-compression" class="section">
 
<div id="incremental-de-compression" class="section">
  
== Incremental (de)compression ==
+
== 增量(解)压缩 ==
  
 
<dl>
 
<dl>
<dt>''class'' <code>bz2.</code><code>BZ2Compressor</code><span class="sig-paren">(</span>''<span class="n">compresslevel</span><span class="o">=</span><span class="default_value">9</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">bz2.</span></span><span class="sig-name descname"><span class="pre">BZ2Compressor</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">compresslevel</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">9</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Create a new compressor object. This object may be used to compress data
+
<dd><p>创建一个新的压缩器对象。 此对象可用于增量压缩数据。 对于一次性压缩,请改用 [[#bz2.compress|compress()]] 函数。</p>
incrementally. For one-shot compression, use the [[#bz2.compress|<code>compress()</code>]] function
+
<p>''compresslevel'',如果给定,必须是 <code>1</code> <code>9</code> 之间的整数。 默认值为 <code>9</code></p>
instead.</p>
 
<p>''compresslevel'', if given, must be an integer between <code>1</code> and <code>9</code>. The
 
default is <code>9</code>.</p>
 
 
<dl>
 
<dl>
<dt><code>compress</code><span class="sig-paren">(</span>''<span class="n">data</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">compress</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">data</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Provide data to the compressor object. Returns a chunk of compressed data
+
<dd><p>向压缩器对象提供数据。 如果可能,返回压缩数据块,否则返回空字节字符串。</p>
if possible, or an empty byte string otherwise.</p>
+
<p>完成向压缩器提供数据后,调用 [[#bz2.BZ2Compressor.flush|flush()]] 方法完成压缩过程。</p></dd></dl>
<p>When you have finished providing data to the compressor, call the
 
[[#bz2.BZ2Compressor.flush|<code>flush()</code>]] method to finish the compression process.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">flush</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Finish the compression process. Returns the compressed data left in
+
<dd><p>完成压缩过程。 返回留在内部缓冲区中的压缩数据。</p>
internal buffers.</p>
+
<p>调用此方法后,可能无法使用压缩器对象。</p></dd></dl>
<p>The compressor object may not be used after this method has been called.</p></dd></dl>
 
 
</dd></dl>
 
</dd></dl>
  
 
<dl>
 
<dl>
<dt>''class'' <code>bz2.</code><code>BZ2Decompressor</code></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">bz2.</span></span><span class="sig-name descname"><span class="pre">BZ2Decompressor</span></span></dt>
<dd><p>Create a new decompressor object. This object may be used to decompress data
+
<dd><p>创建一个新的解压器对象。 该对象可用于增量解压缩数据。 对于一次性压缩,请改用 [[#bz2.decompress|decompress()]] 函数。</p>
incrementally. For one-shot compression, use the [[#bz2.decompress|<code>decompress()</code>]] function
 
instead.</p>
 
 
<div class="admonition note">
 
<div class="admonition note">
  
<p>注解</p>
+
<p>笔记</p>
<p>This class does not transparently handle inputs containing multiple
+
<p>[[#bz2.decompress|decompress()]] [[#bz2.BZ2File|BZ2File]] 不同,此类不会透明地处理包含多个压缩流的输入。 如果您需要使用 [[#bz2.BZ2Decompressor|BZ2Decompressor]] 解压缩多流输入,则必须为每个流使用新的解压缩器。</p>
compressed streams, unlike [[#bz2.decompress|<code>decompress()</code>]] and [[#bz2.BZ2File|<code>BZ2File</code>]]. If
 
you need to decompress a multi-stream input with [[#bz2.BZ2Decompressor|<code>BZ2Decompressor</code>]],
 
you must use a new decompressor for each stream.</p>
 
  
 
</div>
 
</div>
 
<dl>
 
<dl>
<dt><code>decompress</code><span class="sig-paren">(</span>''<span class="n">data</span>'', ''<span class="n">max_length</span><span class="o">=</span><span class="default_value">- 1</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-name descname"><span class="pre">decompress</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">data</span></span>'', ''<span class="n"><span class="pre">max_length</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">-</span> <span class="pre">1</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Decompress ''data'' (a [[../../glossary#term-bytes-like-object|<span class="xref std std-term">bytes-like object</span>]]), returning
+
<dd><p>解压缩 ''data''(一个 [[../../glossary#term-bytes-like-object|bytes-like object]]),以字节形式返回未压缩的数据。 某些 ''data'' 可能会在内部进行缓冲,以供以后调用 [[#bz2.decompress|decompress()]] 时使用。 返回的数据应该与之前对 [[#bz2.decompress|decompress()]] 的任何调用的输出连接在一起。</p>
uncompressed data as bytes. Some of ''data'' may be buffered
+
<p>如果 ''max_length'' 为非负数,则最多返回 ''max_length'' 个字节的解压缩数据。 如果达到此限制并且可以产生更多输出,则 [[#bz2.BZ2Decompressor.needs_input|needs_input]] 属性将设置为 <code>False</code>。 在这种情况下,下一次调用 [[#bz2.BZ2Decompressor.decompress|decompress()]] 可能会提供 ''data'' 作为 <code>b''</code> 以获得更多输出。</p>
internally, for use in later calls to [[#bz2.decompress|<code>decompress()</code>]]. The
+
<p>如果所有输入数据都被解压缩并返回(因为这小于 ''max_length'' 个字节,或者因为 ''max_length'' 是负数),[[#bz2.BZ2Decompressor.needs_input|needs_input]] 属性将是设置为 <code>True</code></p>
returned data should be concatenated with the output of any
+
<p>在到达流末尾后尝试解压缩数据会引发 EOFError。 在流结束后找到的任何数据都将被忽略并保存在 [[#bz2.BZ2Decompressor.unused_data|unused_data]] 属性中。</p>
previous calls to [[#bz2.decompress|<code>decompress()</code>]].</p>
 
<p>If ''max_length'' is nonnegative, returns at most ''max_length''
 
bytes of decompressed data. If this limit is reached and further
 
output can be produced, the [[#bz2.BZ2Decompressor.needs_input|<code>needs_input</code>]] attribute will
 
be set to <code>False</code>. In this case, the next call to
 
[[#bz2.BZ2Decompressor.decompress|<code>decompress()</code>]] may provide ''data'' as <code>b''</code> to obtain
 
more of the output.</p>
 
<p>If all of the input data was decompressed and returned (either
 
because this was less than ''max_length'' bytes, or because
 
''max_length'' was negative), the [[#bz2.BZ2Decompressor.needs_input|<code>needs_input</code>]] attribute
 
will be set to <code>True</code>.</p>
 
<p>Attempting to decompress data after the end of stream is reached
 
raises an EOFError. Any data found after the end of the
 
stream is ignored and saved in the [[#bz2.BZ2Decompressor.unused_data|<code>unused_data</code>]] attribute.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.5 版更改: </span>Added the ''max_length'' parameter.</p>
+
<p><span class="versionmodified changed"> 3.5 版更改: </span> 添加 ''max_length'' 参数。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>eof</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">eof</span></span></dt>
<dd><p><code>True</code> if the end-of-stream marker has been reached.</p>
+
<dd><p><code>True</code> 如果已到达流结束标记。</p>
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.3 新版功能.</span></p>
+
<p><span class="versionmodified added">3.3 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>unused_data</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">unused_data</span></span></dt>
<dd><p>Data found after the end of the compressed stream.</p>
+
<dd><p>在压缩流结束后找到的数据。</p>
<p>If this attribute is accessed before the end of the stream has been
+
<p>如果在到达流末尾之前访问此属性,则其值将为 <code>b''</code></p></dd></dl>
reached, its value will be <code>b''</code>.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>needs_input</code></dt>
+
<dt><span class="sig-name descname"><span class="pre">needs_input</span></span></dt>
<dd><p><code>False</code> if the [[#bz2.BZ2Decompressor.decompress|<code>decompress()</code>]] method can provide more
+
<dd><p><code>False</code> 如果 [[#bz2.BZ2Decompressor.decompress|decompress()]] 方法可以在需要新的未压缩输入之前提供更多的解压缩数据。</p>
decompressed data before requiring new uncompressed input.</p>
 
 
<div class="versionadded">
 
<div class="versionadded">
  
<p><span class="versionmodified added">3.5 新版功能.</span></p>
+
<p><span class="versionmodified added">3.5 版中的新功能。</span></p>
  
 
</div></dd></dl>
 
</div></dd></dl>
第242行: 第185行:
 
<div id="one-shot-de-compression" class="section">
 
<div id="one-shot-de-compression" class="section">
  
== One-shot (de)compression ==
+
== 一次性(解)压缩 ==
  
 
<dl>
 
<dl>
<dt><code>bz2.</code><code>compress</code><span class="sig-paren">(</span>''<span class="n">data</span>'', ''<span class="n">compresslevel</span><span class="o">=</span><span class="default_value">9</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">bz2.</span></span><span class="sig-name descname"><span class="pre">compress</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">data</span></span>'', ''<span class="n"><span class="pre">compresslevel</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">9</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Compress ''data'', a [[../../glossary#term-bytes-like-object|<span class="xref std std-term">bytes-like object</span>]].</p>
+
<dd><p>压缩 ''data'',一个 [[../../glossary#term-bytes-like-object|bytes-like object]]</p>
<p>''compresslevel'', if given, must be an integer between <code>1</code> and <code>9</code>. The
+
<p>''compresslevel'',如果给定,必须是 <code>1</code> <code>9</code> 之间的整数。 默认值为 <code>9</code></p>
default is <code>9</code>.</p>
+
<p>对于增量压缩,请改用 [[#bz2.BZ2Compressor|BZ2Compressor]]</p></dd></dl>
<p>For incremental compression, use a [[#bz2.BZ2Compressor|<code>BZ2Compressor</code>]] instead.</p></dd></dl>
 
  
 
<dl>
 
<dl>
<dt><code>bz2.</code><code>decompress</code><span class="sig-paren">(</span>''<span class="n">data</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">bz2.</span></span><span class="sig-name descname"><span class="pre">decompress</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">data</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Decompress ''data'', a [[../../glossary#term-bytes-like-object|<span class="xref std std-term">bytes-like object</span>]].</p>
+
<dd><p>解压 ''data'',一个 [[../../glossary#term-bytes-like-object|bytes-like object]]</p>
<p>If ''data'' is the concatenation of multiple compressed streams, decompress
+
<p>如果 ''data'' 是多个压缩流的串联,则解压所有流。</p>
all of the streams.</p>
+
<p>对于增量解压缩,请改用 [[#bz2.BZ2Decompressor|BZ2Decompressor]]</p>
<p>For incremental decompression, use a [[#bz2.BZ2Decompressor|<code>BZ2Decompressor</code>]] instead.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.3 版更改: </span>Support for multi-stream inputs was added.</p>
+
<p><span class="versionmodified changed"> 3.3 版更改:</span> 添加了对多流输入的支持。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
第268行: 第209行:
  
 
<span id="bz2-usage-examples"></span>
 
<span id="bz2-usage-examples"></span>
== Examples of usage ==
+
== 使用示例 ==
 
 
Below are some examples of typical usage of the [[#module-bz2|<code>bz2</code>]] module.
 
 
 
Using [[#bz2.compress|<code>compress()</code>]] and [[#bz2.decompress|<code>decompress()</code>]] to demonstrate round-trip compression:
 
 
 
<div class="doctest highlight-default notranslate">
 
 
 
<div class="highlight">
 
  
<pre>&gt;&gt;&gt; import bz2</pre>
+
以下是 [[#module-bz2|bz2]] 模块典型用法的一些示例。
  
</div>
+
使用 [[#bz2.compress|compress()]] 和 [[#bz2.decompress|decompress()]] 来演示往返压缩:
  
</div>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; data = b&quot;&quot;&quot;\
+
<syntaxhighlight lang="python">>>> import bz2
 +
>>> data = b"""\
 
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
 
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
 
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
 
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
第294行: 第227行:
 
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
 
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
 
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
 
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum.&quot;&quot;&quot;</pre>
+
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
 
+
>>> c = bz2.compress(data)
</div>
+
>>> len(data) / len(c)  # Data compression ratio
 
+
1.513595166163142
</div>
+
>>> d = bz2.decompress(c)
<div class="doctest highlight-default notranslate">
+
>>> data == d  # Check equality to original object after round-trip
 
+
True</syntaxhighlight>
<div class="highlight">
 
 
 
<pre>&gt;&gt;&gt; c = bz2.compress(data)
 
&gt;&gt;&gt; len(data) / len(c)  # Data compression ratio
 
1.513595166163142</pre>
 
 
 
</div>
 
 
 
</div>
 
<div class="doctest highlight-default notranslate">
 
 
 
<div class="highlight">
 
 
 
<pre>&gt;&gt;&gt; d = bz2.decompress(c)
 
&gt;&gt;&gt; data == d  # Check equality to original object after round-trip
 
True</pre>
 
 
 
</div>
 
  
 
</div>
 
</div>
Using [[#bz2.BZ2Compressor|<code>BZ2Compressor</code>]] for incremental compression:
 
 
<div class="doctest highlight-default notranslate">
 
 
<div class="highlight">
 
 
<pre>&gt;&gt;&gt; import bz2</pre>
 
  
 
</div>
 
</div>
 +
使用 [[#bz2.BZ2Compressor|BZ2Compressor]] 进行增量压缩:
  
</div>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; def gen_data(chunks=10, chunksize=1000):
+
<syntaxhighlight lang="python">>>> import bz2
...    &quot;&quot;&quot;Yield incremental blocks of chunksize bytes.&quot;&quot;&quot;
+
>>> def gen_data(chunks=10, chunksize=1000):
 +
...    """Yield incremental blocks of chunksize bytes."""
 
...    for _ in range(chunks):
 
...    for _ in range(chunks):
...        yield b&quot;z&quot; * chunksize
+
...        yield b"z" * chunksize
 
...
 
...
&gt;&gt;&gt; comp = bz2.BZ2Compressor()
+
>>> comp = bz2.BZ2Compressor()
&gt;&gt;&gt; out = b&quot;&quot;
+
>>> out = b""
&gt;&gt;&gt; for chunk in gen_data():
+
>>> for chunk in gen_data():
 
...    # Provide data to the compressor object
 
...    # Provide data to the compressor object
 
...    out = out + comp.compress(chunk)
 
...    out = out + comp.compress(chunk)
 
...
 
...
&gt;&gt;&gt; # Finish the compression process.  Call this once you have
+
>>> # Finish the compression process.  Call this once you have
&gt;&gt;&gt; # finished providing data to the compressor.
+
>>> # finished providing data to the compressor.
&gt;&gt;&gt; out = out + comp.flush()</pre>
+
>>> out = out + comp.flush()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The example above uses a very &quot;nonrandom&quot; stream of data
+
上面的示例使用了一个非常“非随机”的数据流(b”z” 块的流)。 随机数据往往压缩得不好,而有序、重复的数据通常会产生很高的压缩率。
(a stream of b&quot;z&quot; chunks). Random data tends to compress poorly,
 
while ordered, repetitive data usually yields a high compression ratio.
 
 
 
Writing and reading a bzip2-compressed file in binary mode:
 
 
 
<div class="doctest highlight-default notranslate">
 
 
 
<div class="highlight">
 
 
 
<pre>&gt;&gt;&gt; import bz2</pre>
 
  
</div>
+
以二进制模式写入和读取 bzip2 压缩文件:
  
</div>
 
 
<div class="doctest highlight-default notranslate">
 
<div class="doctest highlight-default notranslate">
  
 
<div class="highlight">
 
<div class="highlight">
  
<pre>&gt;&gt;&gt; data = b&quot;&quot;&quot;\
+
<syntaxhighlight lang="python">>>> import bz2
 +
>>> data = b"""\
 
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
 
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
 
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
 
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
第380行: 第279行:
 
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
 
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
 
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
 
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum.&quot;&quot;&quot;</pre>
+
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
 
+
>>> with bz2.open("myfile.bz2", "wb") as f:
</div>
 
 
 
</div>
 
<div class="doctest highlight-default notranslate">
 
 
 
<div class="highlight">
 
 
 
<pre>&gt;&gt;&gt; with bz2.open(&quot;myfile.bz2&quot;, &quot;wb&quot;) as f:
 
 
...    # Write compressed data to file
 
...    # Write compressed data to file
...    unused = f.write(data)</pre>
+
...    unused = f.write(data)
 
+
>>> with bz2.open("myfile.bz2", "rb") as f:
</div>
+
...    # Decompress data from file
 +
...    content = f.read()
 +
>>> content == data  # Check equality to original object after round-trip
 +
True</syntaxhighlight>
  
 
</div>
 
</div>
<div class="doctest highlight-default notranslate">
 
 
<div class="highlight">
 
 
<pre>&gt;&gt;&gt; with bz2.open(&quot;myfile.bz2&quot;, &quot;rb&quot;) as f:
 
...    # Decompress data from file
 
...    content = f.read()</pre>
 
  
 
</div>
 
</div>
  
 
</div>
 
</div>
<div class="doctest highlight-default notranslate">
 
 
<div class="highlight">
 
 
<pre>&gt;&gt;&gt; content == data  # Check equality to original object after round-trip
 
True</pre>
 
  
 
</div>
 
</div>
 +
<div class="clearer">
  
</div>
 
  
</div>
 
  
 
</div>
 
</div>
  
[[Category:Python 3.9 中文文档]]
+
[[Category:Python 3.9 文档]]

2021年10月31日 (日) 04:51的最新版本

bz2 — 支持 bzip2 压缩

源代码: :source:`Lib/bz2.py`



该模块提供了一个使用 bzip2 压缩算法压缩和解压缩数据的综合接口。

bz2 模块包含:

该模块中的所有类都可以安全地从多个线程访问。

(解)压缩文件

bz2.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)

以二进制或文本模式打开 bzip2 压缩文件,返回 文件对象

BZ2File 的构造函数一样,filename 参数可以是实际的文件名(strbytes 对象),也可以是现有的要读取或写入的文件对象。

mode 参数可以是 'r''rb''w''wb''x''xb''a''ab' 用于二进制模式,或 'rt''wt''xt' 或 ] 用于文本模式。 默认值为 'rb'

compresslevel 参数是一个从 1 到 9 的整数,对于 BZ2File 构造函数。

对于二进制模式,此函数等效于 BZ2File 构造函数:BZ2File(filename, mode, compresslevel=compresslevel)。 在这种情况下,不得提供 encodingerrorsnewline 参数。

对于文本模式,会创建一个 BZ2File 对象,并将其包装在具有指定编码、错误处理行为和行尾的 io.TextIOWrapper 实例中。

3.3 版中的新功能。

3.4版本变更:增加了'x'(独创)模式。

3.6 版更改: 接受 类路径对象

class bz2.BZ2File(filename, mode='r', *, compresslevel=9)

以二进制模式打开 bzip2 压缩文件。

如果 filenamestrbytes 对象,则直接打开命名文件。 否则,filename 应该是一个 file object,它将用于读取或写入压缩数据。

mode 参数可以是用于读取的 'r'(默认)、用于覆盖的 'w'、用于独占创建的 'x''a'用于附加。 这些可以分别等效地表示为 'rb''wb''xb''ab'

如果 filename 是文件对象(而不是实际文件名),则 'w' 模式不会截断文件,而是等效于 'a'

如果 mode'w''a',则 compresslevel 可以是 19 之间的整数,指定压缩级别:1 产生的压缩最少,而 9(默认)产生的压缩最多。

如果mode'r',则输入文件可能是多个压缩流的串联。

BZ2File 提供了 io.BufferedIOBase 指定的所有成员,除了 detach()truncate()。 支持迭代和 with 语句。

BZ2File 还提供了如下方法:

peek([n])

返回缓冲数据而不推进文件位置。 至少会返回一个字节的数据(除非在 EOF 处)。 返回的确切字节数未指定。

笔记

虽然调用 peek() 不会改变 BZ2File 的文件位置,但它可能会改变底层文件对象的位置(例如 如果 BZ2File 是通过为 filename 传递文件对象来构造的)。

3.3 版中的新功能。

3.1 版更改: 添加了对 with 语句的支持。

3.3 版本变更:fileno()readable()seekable()writable()read1()readinto() 方法。

3.3 版更改: 支持 文件名文件对象 而不是实际文件名。

3.3 版本变更: 添加了 'a'(追加)模式,并支持读取多流文件。

3.4版本变更:增加了'x'(独创)模式。

3.5 版更改: read() 方法现在接受 None 的参数。

3.6 版更改: 接受 类路径对象

3.9 版更改: 删除了 缓冲 参数。 自 Python 3.0 以来,它被忽略和弃用。 传递一个打开的文件对象来控制文件的打开方式。

compresslevel 参数变为仅限关键字。


增量(解)压缩

class bz2.BZ2Compressor(compresslevel=9)

创建一个新的压缩器对象。 此对象可用于增量压缩数据。 对于一次性压缩,请改用 compress() 函数。

compresslevel,如果给定,必须是 19 之间的整数。 默认值为 9

compress(data)

向压缩器对象提供数据。 如果可能,返回压缩数据块,否则返回空字节字符串。

完成向压缩器提供数据后,调用 flush() 方法完成压缩过程。

flush()

完成压缩过程。 返回留在内部缓冲区中的压缩数据。

调用此方法后,可能无法使用压缩器对象。

class bz2.BZ2Decompressor

创建一个新的解压器对象。 该对象可用于增量解压缩数据。 对于一次性压缩,请改用 decompress() 函数。

笔记

decompress()BZ2File 不同,此类不会透明地处理包含多个压缩流的输入。 如果您需要使用 BZ2Decompressor 解压缩多流输入,则必须为每个流使用新的解压缩器。

decompress(data, max_length=- 1)

解压缩 data(一个 bytes-like object),以字节形式返回未压缩的数据。 某些 data 可能会在内部进行缓冲,以供以后调用 decompress() 时使用。 返回的数据应该与之前对 decompress() 的任何调用的输出连接在一起。

如果 max_length 为非负数,则最多返回 max_length 个字节的解压缩数据。 如果达到此限制并且可以产生更多输出,则 needs_input 属性将设置为 False。 在这种情况下,下一次调用 decompress() 可能会提供 data 作为 b 以获得更多输出。

如果所有输入数据都被解压缩并返回(因为这小于 max_length 个字节,或者因为 max_length 是负数),needs_input 属性将是设置为 True

在到达流末尾后尝试解压缩数据会引发 EOFError。 在流结束后找到的任何数据都将被忽略并保存在 unused_data 属性中。

3.5 版更改: 添加 max_length 参数。

eof

True 如果已到达流结束标记。

3.3 版中的新功能。

unused_data

在压缩流结束后找到的数据。

如果在到达流末尾之前访问此属性,则其值将为 b

needs_input

False 如果 decompress() 方法可以在需要新的未压缩输入之前提供更多的解压缩数据。

3.5 版中的新功能。


一次性(解)压缩

bz2.compress(data, compresslevel=9)

压缩 data,一个 bytes-like object

compresslevel,如果给定,必须是 19 之间的整数。 默认值为 9

对于增量压缩,请改用 BZ2Compressor

bz2.decompress(data)

解压 data,一个 bytes-like object

如果 data 是多个压缩流的串联,则解压所有流。

对于增量解压缩,请改用 BZ2Decompressor

3.3 版更改: 添加了对多流输入的支持。


使用示例

以下是 bz2 模块典型用法的一些示例。

使用 compress()decompress() 来演示往返压缩:

>>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> c = bz2.compress(data)
>>> len(data) / len(c)  # Data compression ratio
1.513595166163142
>>> d = bz2.decompress(c)
>>> data == d  # Check equality to original object after round-trip
True

使用 BZ2Compressor 进行增量压缩:

>>> import bz2
>>> def gen_data(chunks=10, chunksize=1000):
...     """Yield incremental blocks of chunksize bytes."""
...     for _ in range(chunks):
...         yield b"z" * chunksize
...
>>> comp = bz2.BZ2Compressor()
>>> out = b""
>>> for chunk in gen_data():
...     # Provide data to the compressor object
...     out = out + comp.compress(chunk)
...
>>> # Finish the compression process.  Call this once you have
>>> # finished providing data to the compressor.
>>> out = out + comp.flush()

上面的示例使用了一个非常“非随机”的数据流(b”z” 块的流)。 随机数据往往压缩得不好,而有序、重复的数据通常会产生很高的压缩率。

以二进制模式写入和读取 bzip2 压缩文件:

>>> import bz2
>>> data = b"""\
... Donec rhoncus quis sapien sit amet molestie. Fusce scelerisque vel augue
... nec ullamcorper. Nam rutrum pretium placerat. Aliquam vel tristique lorem,
... sit amet cursus ante. In interdum laoreet mi, sit amet ultrices purus
... pulvinar a. Nam gravida euismod magna, non varius justo tincidunt feugiat.
... Aliquam pharetra lacus non risus vehicula rutrum. Maecenas aliquam leo
... felis. Pellentesque semper nunc sit amet nibh ullamcorper, ac elementum
... dolor luctus. Curabitur lacinia mi ornare consectetur vestibulum."""
>>> with bz2.open("myfile.bz2", "wb") as f:
...     # Write compressed data to file
...     unused = f.write(data)
>>> with bz2.open("myfile.bz2", "rb") as f:
...     # Decompress data from file
...     content = f.read()
>>> content == data  # Check equality to original object after round-trip
True