]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Issue #24496: Backport gzip examples to Python 2.
authorBerker Peksag <berker.peksag@gmail.com>
Thu, 25 Jun 2015 20:57:42 +0000 (23:57 +0300)
committerBerker Peksag <berker.peksag@gmail.com>
Thu, 25 Jun 2015 20:57:42 +0000 (23:57 +0300)
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.

Doc/library/gzip.rst

index e26fe286c40a6862910e8796e143e0ceae36ff63..7c16d3ae2495bf69a2f811992a8d254e6a6691ee 100644 (file)
@@ -96,26 +96,22 @@ Examples of usage
 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::