Search code examples
pythonziparchive

Build variable into python zip script


Before I start, I am trying to create a python zip script which will take a snapshot of the target_dir, zip it, save it in the temp folder and give it the filename of "now" variable. This is the code I have:

#!/usr/bin/env python

import os
import sys
import datetime

now = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M")
target_dir = '/var/lib/data'
temp_dir='/tmp'

zip = zipfile.ZipFile('/tmp/example.zip', 'w', zipfile.ZIP_DEFLATED)
rootlen = len(target_dir) + 1
for base, dirs, files in os.walk(target_dir):
   for file in files:
      fn = os.path.join(base, file)
      zip.write(fn, fn[rootlen:])

I can't figure out how to get this line to instead use the variable "now" and "temp_dir" instead of hardcoding the destination:

zip = zipfile.ZipFile('/tmp/example.zip', 'w', zipfile.ZIP_DEFLATED)

I guess I want something like this (pseudo code):

zip = zipfile.ZipFile('<temp_dir>/<now>.zip', 'w', zipfile.ZIP_DEFLATED)

Can anyone show me how this should be done?


Solution

  • Python string formating lets you put the content of variables into strings, that would be

    zip = zipfile.ZipFile('%s/%s.zip' % (temp_dir, now), 'w', zipfile.ZIP_DEFLATED)
    

    String formating replaces the occurences of "%s" with the strings in the tuple after the formating operator %.

    Alternatively (and cleaner), use the same os.path.join you use later in your code:

    zip = zipfile.ZipFile(os.path.join(temp_dir, now+".zip"), 'w', zipfile.ZIP_DEFLATED)
    

    os.path.join is a function that glues together elements of a file system path according to whatever logic your file system uses, so it would use \ instead of / in operating systems that use that character in paths. String concatenation is just +, so to glue the file ending .zip to another string now, now+".zip" just does the trick.