Skip to Content
Python in a Nutshell
book

Python in a Nutshell

by Alex Martelli
March 2003
Intermediate to advanced
656 pages
39h 30m
English
O'Reilly Media, Inc.
Content preview from Python in a Nutshell

Name

open

Synopsis

open(filename,mode='rb',compresslevel=9)

Like GzipFile( filename,mode,compresslevel ), but filename is mandatory and there is no provision for passing an already opened fileobj.

Say that you have some function f ( x ) that writes data to a text file object x, typically by calling x .write and/or x .writelines. Getting f to write data to a gzip-compressed text file instead is easy:

import gzip
underlying_file = open('x.txt.gz', 'wb')
compressing_wrapper = gzip.GzipFile(fileobj=underlying_file, mode='wt')
f(compressing_wrapper)
compressing_wrapper.close( )
underlying_file.close( )

This example opens the underlying binary file x.txt.gz and explicitly wraps it with gzip.GzipFile, and thus, at the end, we need to close each object separately. This is necessary because we want to use two different modes: the underlying file must be opened in binary mode (any translation of line endings would produce an invalid compressed file), but the compressing wrapper must be opened in text mode because we want the implicit translation of os.linesep to \n. Reading back a compressed text file, for example to display it on standard output, is similar:

import gzip, xreadlines
underlying_file = open('x.txt.gz', 'rb')
uncompressing_wrapper = gzip.GzipFile(fileobj= underlying_file, mode='rt')
for line in xreadlines.xreadlines(uncompressing_wrapper):
    print line,
uncompressing_wrapper.close( )
underlying_file.close( )

This example uses module xreadlines, covered earlier in this chapter, because ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python in a Nutshell, 3rd Edition

Python in a Nutshell, 3rd Edition

Alex Martelli, Anna Ravenscroft, Steve Holden
Python in a Nutshell, 4th Edition

Python in a Nutshell, 4th Edition

Alex Martelli, Anna Martelli Ravenscroft, Steve Holden, Paul McGuire
Data Wrangling with Python

Data Wrangling with Python

Jacqueline Kazil, Katharine Jarmul

Publisher Resources

ISBN: 0596001886Supplemental ContentCatalog PageErrata