'How to zip a file to STDOUT with zipfile?
I have a program that creates a zip file containing a couple of files using zipfile. It takes an output filename as argument, but if no file or -
is given, it should write to STDOUT. But if I pass sys.stdout
as file parameter to ZipFile, it gives me the following error:
File "/usr/lib/python2.7/zipfile.py", line 775, in __init__
self._start_disk = self.fp.tell()
IOError: [Errno 29] Illegal seek
Here's my code:
import zipfile, sys
def myopen(name, mode='r'):
if name is not None:
try: return open(name, mode)
except EnvironmentError as e:
print >> sys.stderr, '%s: %s' % (name, e.strerror)
sys.exit(3)
elif mode == 'r': return sys.stdin
elif mode in 'aw': return sys.stdout
else: return None
outfile = None
# build the files ...
files = {'file1': 'Here is an example file.\n', 'file2': 'Some more ...'}
with myopen(outfile, 'w') as f, zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED, True) as zf:
for name, content in files.iteritems(): zf.writestr(name, content)
How can I make this work?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|