diff options
author | Nadeem Vawda <nadeem.vawda@gmail.com> | 2012-06-04 21:21:38 (GMT) |
---|---|---|
committer | Nadeem Vawda <nadeem.vawda@gmail.com> | 2012-06-04 21:21:38 (GMT) |
commit | 68721019efb16ba8acad036c331a9a195d6f7da0 (patch) | |
tree | 3fad6d5d15ea939af5327415a1cae0de9a80956d /Lib/gzip.py | |
parent | d7b7c7472b274c6867261b3a796c2aada9945849 (diff) | |
download | cpython-68721019efb16ba8acad036c331a9a195d6f7da0.zip cpython-68721019efb16ba8acad036c331a9a195d6f7da0.tar.gz cpython-68721019efb16ba8acad036c331a9a195d6f7da0.tar.bz2 |
Add fileobj support to gzip.open().
Diffstat (limited to 'Lib/gzip.py')
-rw-r--r-- | Lib/gzip.py | 13 |
1 files changed, 12 insertions, 1 deletions
diff --git a/Lib/gzip.py b/Lib/gzip.py index 2f53aa8..412bf05 100644 --- a/Lib/gzip.py +++ b/Lib/gzip.py @@ -20,6 +20,9 @@ def open(filename, mode="rb", compresslevel=9, encoding=None, errors=None, newline=None): """Open a gzip-compressed file in binary or text mode. + The filename argument can be an actual filename (a str or bytes object), or + an existing file object to read from or write to. + The mode argument can be "r", "rb", "w", "wb", "a" or "ab" for binary mode, or "rt", "wt" or "at" for text mode. The default mode is "rb", and the default compresslevel is 9. @@ -43,7 +46,15 @@ def open(filename, mode="rb", compresslevel=9, raise ValueError("Argument 'errors' not supported in binary mode") if newline is not None: raise ValueError("Argument 'newline' not supported in binary mode") - binary_file = GzipFile(filename, mode.replace("t", ""), compresslevel) + + gz_mode = mode.replace("t", "") + if isinstance(filename, (str, bytes)): + binary_file = GzipFile(filename, gz_mode, compresslevel) + elif hasattr(filename, "read") or hasattr(filename, "write"): + binary_file = GzipFile(None, gz_mode, compresslevel, filename) + else: + raise TypeError("filename must be a str or bytes object, or a file") + if "t" in mode: return io.TextIOWrapper(binary_file, encoding, errors, newline) else: |