tedioustortoise
tedioustortoise

Reputation: 269

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

Upvotes: 2

Views: 1072

Answers (2)

chuckx
chuckx

Reputation: 6937

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 +.

Upvotes: 2

Elis Byberi
Elis Byberi

Reputation: 1452

You have to properly format command line command 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")

Upvotes: 1

Related Questions