Creating a .zip archive with Python in MS DOS - python

I am new to programming. I am trying to learn Python using CH Swaroop's "Byte of Python". One example is to create a program which will backup some files from one directory to another and compress them into a .zip format. Unfortunately the example he gives is only helpful if you happen to be a linux/unix user. For windows users he says only "Windows users can use the Info-Zip program" but doesn't elaborate further. This is the code he provides ...
#!/usr/bin/python
# Filename : backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = [r'C:\Users\ClickityCluck\Documents']
# 2. The backup must be stored in a main backup directory
target_dir = r'C:\Backup'
# 3. Zip seems good
# 4. Let's make the name of the file the current date/time
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip command to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ''.join(source))
# Run Backup
if os.system(zip_command) == 0:
print "Succesful backup to", target
else:
print 'BACKUP FAILED :('
Can anyone lay out for me a way to do this in the command line on windows 7? Thank you for your time and I apologize in advance if I have failed to provide some pertinent information :)

For python 3 users and using the format method answer should be:
# 1. The files and directories to be backed up are specified in a list.
source = [r'C\Users\MySourceDir']
# 2. The backup must be stored in a # main backup directory
target_dir = r'C:\Users\MyTargetDir'
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.7z'
# Create target directory if it is not present
if not os.path.exists(target_dir):
os.mkdir(target_dir)
# 5. We use the zip command to put the files in a zip archive
zip_command = 'C:\\"Program Files"\\7-Zip\\7z a -t7z -r "{0}" "{1}"'.format(target,' '.join(source)) # be careful with spaces on each dir specification. Problems could arise if double-quotation marks aren't between them.
# Run the backup
print('Zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')

zip is command line utility to create/update/extract ZIP archives, available on Unix/Linux/Mac OS X. If you want to archive files using a command line utility, you should find and install an appropriate on (compress, for example, is a part of resource kit).
The another way is to use python's zipfile module and make a useful command-line utility for windows :)
BTW, why your question refers to MS DOS?

#!/usr/bin/python -tt
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['C:\\Documents\\working_projects\\', 'C:\\Documents\\hot_tips\\']
# 2. The back up must be stored in a main back directory
target_dir = 'C:\\temp\\backup\\'
# 3. The files are backed up into a zip file
# 4. The name of the zip archive is the current date and time
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.7z'
# 5. We use the zip command to put the files in a zip archive
#zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
zip_command = 'C:\\"Program Files"\\7-Zip\\7z a -t7z "%s" %s' % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful back up to', target
else:
print 'Backup FAILED'

Related

How to determine error when Python print(os.system("command")) in Windows

I followed the directions in the Byte of Python book, regarding creating a program for backups.
At the end of it, my python code keeps returning Backup FAILED. I had it print the error, which it gave: -1073741515
I've searched and searched and can't seem to find an answer to the meaning of the error code. See the python code below:
import os
import time
# 1. The files and directories to be backed up are
# specified in a list.
# Example on Windows:
source = [r'C:\Users\ftbbo\PycharmProjects\helloworld']
# Example on Mac OS X and linux:
# source = ['/Users/swa/notes']
# Notice we have to use double quotes inside a string
# for names with spaces in it. We could have also used
# a raw string by writing [r'C:\My Documents'].
# 2. The backup must be stored in a
# main backup directory
# Example on Windows:
target_dir = 'C:\\PyBackup'
# Example on Max OS X and Linux:
# target_dir = '/Users/swa/backup'
# Remember to change this to which folder you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + os.sep + \
time.strftime('%Y%m%d%H%M%S') + '.zip'
# Create target directory if it is not present
if not os.path.exists(target_dir):
os.mkdir(target_dir) # make directory
# 5. We use the zip command to put the files in a zip archive
zip_command = 'zip -r {0} {1}'.format(target,
' '.join(source))
# -r = recursive
# Run the backup
print('Zip command is:')
print(zip_command)
print('Running:')
print(os.system(zip_command)) # I added this to try to troubleshoot the error
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
# Still can't figure out what the error code -1073741515 means

why in the famous backup python script, it doesn't work when target folder name contains spaces?

hello everyone: this is the famous code for backing up files. It works fine giving me the message ( successful back up ). the target directory is created, but it is empty.
But when I remove spaces from the target folder name it worked very fine. so, what is the problem and how to use target folders with spaces ?
enter code here
import os
import time
source = [r'D:\python35']
target_dir = r"D:\Backup to harddisk 2016"
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip'
if not os.path.exists(target_dir):
os.mkdir(target_dir)
zip_command = "zip -r {0} {1}".format(target, ' '.join(source))
print('zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
The problem is that Windows doesn't know that those spaces are part of the file name. Use subprocess.call, which takes a list of parameters instead. On Windows, it escapes the spaces for you before calling CreateProcess.
import subprocess as subp
zip_command = ["zip", "-r", target] + source
if subp.call(zip_command) == 0:
print('Successful backup to', target)
It looks like it uses the command line: "zip -r {0} {1}".format(target, ' '.join(source).
Spaces are used to separate arguments on the command line. If there's a space within the name, it believes it's the start of another argument.

zip error: Invalid command arguments (cannot write zip file to terminal)

I am learning the book A Bite of Python. After typing in the example in the book
import os
import time
# 1. The files and directories to be backed up are
# specified in a list.
# Example on Windows:
# source = ['"C:\\MY Documents"', 'C:\\Code']
# Example on Mac OS X and Linux:
source = ['/home/username/Downloads/books']
# Notice we had to use double quotes inside the string
# for names with spaces in it.
# 2. The backup must be stored in a
# main backup directory
# Example on Windows:
# target_dir = 'E:\\Backup'
# Example on Mac OS X and Linux:
target_dir = '/home/username/Downloads/backup'
# Remember to change this to which folder you will be using
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + os.sep + \
time.strftime('%Y%m%d%H%M%S') + '.zip'
# Create target directory if it is not present
if not os.path.exists(target_dir):
os.mkdir(target_dir) # make directory
# 5. We use the zip commond to put the files in a zip archive
zip_command = "zip - r {0} {1}".format(target, ' '.join(source))
# Run the backup
print "Zip command is:"
print zip_command
print "Running:"
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FALIED'
I goe a message zip error: Invalid command arguments (cannot write zip file to terminal)
I can not figure out where goes wrong, I type in the same code in this book.
Anyone knows why this happen?
The issue is in the zip command you are creating , there is an extra space between - and r . Example -
zip_command = "zip - r {0} {1}".format(target, ' '.join(source))
^
Notice the extra space
There should be no space between - and r. Example -
zip_command = "zip -r {0} {1}".format(target, ' '.join(source))
Also, I would like to suggest that, it would be better to use subprocess.call() rather than os.system , providing it a list of arguments for the command. Example -
import subprocess
zip_command = ['zip','-r',target]
for s in source:
zip_command.append(s)
subprocess.call(zip_command)
It would have been easier to see the error this way.

Creating a backup and getting error only concenate list and not (str)

I'm trying to write a code to create backup of files or directory using Python but there is an error : can only concenate list not "str"
Here's my code :
import os
import time
# The files or directory which has to be backed up
source = ['"F:\\College Stuffs"']
#The backup must be stored in a target directory
target_dir = ['"E:\\Backup"']
#File will be backed up in a zip file and name will be set to current date
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + target.append('.zip')
# Create the directory if it's not present
if not os.path.exists(target_dir):
os.mkdir(target_dir) #Make the directory
#Use zip command to put files in a zip archive
zip_command = "zip -r {} {}".format(target,''.join(source))
#run the backuo
print "Zip command is : "
print zip_command
print "Running:"
if os.system(zip_command) == 0:
print 'Successful backup to', target
else:
print 'Backup FAILED'
You've defined a list
#The backup must be stored in a target directory
target_dir = ['"E:\\Backup"']
while your usage indicates you'd intended to use a str there:
#The backup must be stored in a target directory
target_dir = '"E:\\Backup"'

Python Script to backup a directory

#Filename:backup_ver1
import os
import time
#1 Using list to specify the files and directory to be backed up
source = r'C:\Documents and Settings\rgolwalkar\Desktop\Desktop\Dr Py\Final_Py'
#2 define backup directory
destination = r'C:\Documents and Settings\rgolwalkar\Desktop\Desktop\PyDevResourse'
#3 Setting the backup name
targetBackup = destination + time.strftime('%Y%m%d%H%M%S') + '.rar'
rar_command = "rar.exe a -ag '%s' %s" % (targetBackup, ''.join(source))
##i am sure i am doing something wrong here - rar command please let me know
if os.system(rar_command) == 0:
print 'Successful backup to', targetBackup
else:
print 'Backup FAILED'
O/P:- Backup FAILED
winrar is added to Path and CLASSPATH under Environment variables as well - anyone else with a suggestion for backing up the directory is most welcome
Maybe instead of writing your own backup script you could use python tool called rdiff-backup, which can create incremental backups?
The source directory contains spaces, but you don't have quotes around it in the command line. This might be a reason for the backup to fail.
To avoid problems like this, use the subprocess module instead of os.system:
subprocess.call(['rar.exe', 'a', '-ag', targetBackup, source])
if the compression algorithm can be something else and its just to backup a directory, why not do it with python's own tar and gzip instead? eg
import os
import tarfile
import time
root="c:\\"
source=os.path.join(root,"Documents and Settings","rgolwalkar","Desktop","Desktop","Dr Py","Final_Py")
destination=os.path.join(root,"Documents and Settings","rgolwalkar","Desktop","Desktop","PyDevResourse")
targetBackup = destination + time.strftime('%Y%m%d%H%M%S') + 'tar.gz'
tar = tarfile.open(targetBackup, "w:gz")
tar.add(source)
tar.close()
that way, you are not dependent on rar.exe on the system.

Categories

Resources