[Python-checkins] cpython (2.7): Issue #24496: Backport gzip examples to Python 2.

berker.peksag python-checkins at python.org
Thu Jun 25 22:56:48 CEST 2015


https://hg.python.org/cpython/rev/10eea15880db
changeset:   96682:10eea15880db
branch:      2.7
user:        Berker Peksag <berker.peksag at gmail.com>
date:        Thu Jun 25 23:57:42 2015 +0300
summary:
  Issue #24496: Backport gzip examples to Python 2.

gzip.open() supports context management protocol in Python 2, so it's better to
use it in the examples section.

Patch by Jakub Kadlčík.

files:
  Doc/library/gzip.rst |  18 +++++++-----------
  1 files changed, 7 insertions(+), 11 deletions(-)


diff --git a/Doc/library/gzip.rst b/Doc/library/gzip.rst
--- a/Doc/library/gzip.rst
+++ b/Doc/library/gzip.rst
@@ -96,26 +96,22 @@
 Example of how to read a compressed file::
 
    import gzip
-   f = gzip.open('file.txt.gz', 'rb')
-   file_content = f.read()
-   f.close()
+   with gzip.open('file.txt.gz', 'rb') as f:
+       file_content = f.read()
 
 Example of how to create a compressed GZIP file::
 
    import gzip
    content = "Lots of content here"
-   f = gzip.open('file.txt.gz', 'wb')
-   f.write(content)
-   f.close()
+   with gzip.open('file.txt.gz', 'wb') as f:
+       f.write(content)
 
 Example of how to GZIP compress an existing file::
 
    import gzip
-   f_in = open('file.txt', 'rb')
-   f_out = gzip.open('file.txt.gz', 'wb')
-   f_out.writelines(f_in)
-   f_out.close()
-   f_in.close()
+   import shutil
+   with open('file.txt', 'rb') as f_in, gzip.open('file.txt.gz', 'wb') as f_out:
+       shutil.copyfileobj(f_in, f_out)
 
 
 .. seealso::

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list