The docs
with ZipFile('spam.zip', 'w') as myzip:
myzip.write('eggs.txt')
Example
Extract one file (the first) from each .zip file.
from zipfile import ZipFile
from glob import glob
import os
zs = glob("*.zip")
os.makedirs("samples",exist_ok=True)
for i,z in enumerate(zs):
x = z.split(".")[0]
with ZipFile(z,"r") as f:
nl = f.namelist()
n = nl[0]
ofn = f"samples/{n}"
with f.open(n,"r") as g:
data = g.read()
with open(ofn,"wb") as g:
g.write(data)
print(f"{i}/{len(zs)} {n}")
Updating an archive
You need to write to a new archive, copying all those files you don't want to change. This example modifies a single line in a single text file in a Reaper theme. (I don't recommend actually running this. It is offered as example code.)
#!/usr/bin/env python
import sys
from zipfile import ZipFile
import os
import re
args = sys.argv[1:]
try:
zfn, ozfn, newsize = args
newsize = int(newsize)
except ValueError:
print(f"{sys.argv[0]} <zipfilename> <outzipfilename> <newsize>")
exit(1)
fn = "Default_7.0_unpacked/rtconfig.txt"
with ZipFile(zfn,"r") as zf:
with zf.open(fn,"r") as rt:
rtd = rt.read()
lines = rtd.decode().splitlines()
for i,line in enumerate(lines):
if "LayoutA-tcpLabelLength" in line:
sep = "'Layout A - TCP Label Length'"
l,r = line.split(sep,1)
r = re.sub('\d+',str(newsize),r,count=1)
line = sep.join((l,r))
lines[i] = line
break
else:
print(f"Couldn't find the line to change")
exit(2)
rtd = "\r\n".join(lines).encode()
with ZipFile(zfn,"r") as zfi:
with ZipFile(ozfn,"w") as zfo:
nl = zfi.namelist()
for x in nl:
if x == fn:
zfo.writestr(fn,rtd,compresslevel=0)
else:
with zfi.open(x,"r") as f:
data = f.read()
with zfo.open(x,"w") as f:
f.write(data)
print("Written",ozfn)