Search code examples
pythonzipos.system

Os.system() - Changing zip command to give a different file name for various datetimes


I am trying to zip a directory with a date-time stamp added to the created zip folder. How would I go about doing this? I have tried something like this:

import datetime   
import os
backup_zip = True
    if backup_zip:
        dt = ('{:%Y%m%d_%H%M}'.format(datetime.datetime.now()))
        name = dt + "folder.zip"
        os.system("zip -r" + name +  "/home/olb/CPL")

This works, but without the date-time stamp:

# os.system("zip -r folder.zip /home/olb/CPL")

Many thanks for any help


Solution

  • You need to make sure there are spaces around the name.

    With your current implementation, the argument being provided to os.system() is:

    zip -r<name>/home/olb/CPL
    

    When instead it should be:

    zip -r <name> /home/olb/CPL
    

    The simplest fix is adding a space before the preceding quote and a space after the following quote:

    os.system("zip -r " + name +  " /home/olb/CPL")
    

    If you're using Python 3.6+, you can use formatted string literals:

    name = f"{dt}folder.zip"
    command = f"zip -r {name} /home/olb/CPL"
    

    This can be easier to deal with versus dealing with quotes and concatenation using +.