473,890 Members | 1,686 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Backup with zips

30 New Member
I am attempting to write a script to zip all directories in current directory into zip files. e.g. [If a directory has 2 folders in it and my script is run in that directory I want it to create two zips (one for each folder) and keep the tree organization in the zip]. Currently I have this...

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/python
  2. # Filename: backup_zip.py
  3.  
  4. import os
  5. import zipfile
  6. import glob
  7.  
  8. r = 1
  9.  
  10. def backup():
  11.  
  12.    cwd = os.getcwd()
  13.  
  14.    # for file in os.walk(cwd):
  15.    for dirpath, dirs, files in os.walk(cwd):
  16.       z_path = os.path.join(dirpath,file) 
  17.    #   docs = open(file, 'r')
  18.       docs = open(z_path, 'r')
  19.       output = zipfile.ZipFile(docs, 'w')
  20.       output.write(docs)
  21.  
  22.    output.close()
  23.  
  24.   # Ignore old code I was messing with \\\\\\\
  25.   # ZipFile(cwd['w'[ZIP_STORED[allowZip64]]]):
  26.   #   z_path = os.path.join(dirpath,file)
  27.   #   start = cwd.rfind(
  28.   #   output.write(z_path,z_path[start:])
  29.   #
  30.   # if file == '*.zip':
  31.   #     
  32.   # else:
  33.   #   output.write(z_path)
  34.   # output.close()
  35.   #
  36.   # output_append.write(z_path)
  37.  
  38. while r == 1:
  39.  
  40.    print "This script when run backs up files in a directory by comressing them to zips. "
  41.    begin = raw_input("Do you wish to back up files in this directory [type: yes or no] ")   
  42.  
  43.    if begin == "yes":
  44.       r = 1
  45.  
  46.       backup()
  47.    elif begin == "no":
  48.       r = 0
  49.    else:
  50.       print "Enter yes or no"
  51.  
  52.  
It is giving me this error..

Expand|Select|Wrap|Line Numbers
  1.     z_path = os.path.join(dirpath,file)
  2.   File "C:\Python25\lib\ntpath.py", line 67, in join
  3.     elif isabs(b):
  4.   File "C:\Python25\lib\ntpath.py", line 53, in isabs
  5.     s = splitdrive(s)[1]
  6.   File "C:\Python25\lib\ntpath.py", line 119, in splitdrive
  7.     if p[1:2] == ':':
  8. TypeError: 'type' object is unsubscriptable
I got this part from another script I saw..

Expand|Select|Wrap|Line Numbers
  1. for dirpath, dirs, files in os.walk(cwd):
  2.       z_path = os.path.join(dirpath,file) 
I don't really know what it does. I know os.walk(cwd) walks through and creates a tuple or list of files in the directories, but I don't understand why dirpath dirs files are in there. (wouldn't it just need dir and file)

Also I don't understand why I need to join dirpath and file.

Please explain how to make this work or why mine doesn't work. Please keep in mind I am new to programming so I won't understand answers with a ton of jargon in them.
Oct 11 '08 #1
4 7601
bvdet
2,851 Recognized Expert Moderator Specialist
You are trying to join the path and the Python built-in file.
Expand|Select|Wrap|Line Numbers
  1. >>> file
  2. <type 'file'>
  3. >>> type(file)
  4. <type 'type'>
  5. >>> help(file)
  6. Help on class file in module __builtin__:
  7.  
  8. class file(object)
  9.  |  file(name[, mode[, buffering]]) -> file object
  10.  |  
  11.  |  Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
Oct 11 '08 #2
bvdet
2,851 Recognized Expert Moderator Specialist
How would ZipFile() find the files if you don't give it the full path? Here's an example:
Expand|Select|Wrap|Line Numbers
  1. import zipfile, os
  2.  
  3. def makeArchive(fileList, archive):
  4.     """
  5.     'fileList' is a list of file names - full path each name
  6.     'archive' is the file name for the archive with a full path
  7.     """
  8.     try:
  9.         # ZipFile will accept a file name or file object
  10.         a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
  11.         for f in fileList:
  12.             print "archiving file %s" % (f)
  13.             a.write(f) # (f, os.path.basename(f))
  14.         a.close()
  15.         return True
  16.     except: return False
Oct 11 '08 #3
Bouzy
30 New Member
When I run your code it doesn't give any errors. However, it doesn't work. When I run this as my code...

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/python
  2. # Filename: backup_zip.py
  3.  
  4. import os, zipfile
  5.  
  6. r = 1
  7.  
  8. while r == 1:
  9.  
  10.    print "This script when run backs up files in a directory by comressing them to zips. "
  11.    begin = raw_input("Do you wish to back up files in this directory [type: yes or no] ")   
  12.  
  13.    if begin == "yes":
  14.       r = 1
  15.       backup()  
  16.    elif begin == "no":
  17.       r = 0
  18.    else:
  19.       print "Enter yes or no"
  20.  
  21. def backup(fileList, archive):
  22.  
  23.    cwd = os.getcwd()
  24. #   archive = os.pathname
  25. #   fileList = dirpath, dirs, files in os.walk(cwd)
  26.    f = os.path.basename
  27.  
  28.    output = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
  29.  
  30.    for f in fileList:
  31.       print "archiving file '%s'" % (f)
  32.       output.write(f)
  33.    output.close()
  34.  
  35. if __name__ == "__main__":
  36.    backup()
  37.  
  38.  
  39.  
  40.  
it gives me this error...

Expand|Select|Wrap|Line Numbers
  1. Traceback (most recent call last):
  2.   File "C:\Documents and Settings\Gabe\Desktop\test\backup_zip.py", line 15, in <module>
  3.     backup()
  4. TypeError: backup() takes exactly 2 arguments (0 given)
I don't understand because you didn't define fileList or archive as a variable outside of the function (which is an argument right) Neither do i, but your code runs..?

Basically at this point my code is similar to yours but doens't run. I don't know what the error it gives means, and your code runs but doesn't create a zip file..
Oct 11 '08 #4
bvdet
2,851 Recognized Expert Moderator Specialist
You have to pass arguments to backup(). Regarding my code - when you run it, the function object is created, but is not called. Here's a an example of calling the function and passing arguments:
Expand|Select|Wrap|Line Numbers
  1. if __name__== '__main__':
  2.  
  3.     fileList = [r'D:\Miscellaneous\Toll Plaza Iso1.bmp',
  4.                 r'D:\Miscellaneous\Io_Volcano_Plume.jpg',
  5.                 r'D:\Miscellaneous\Dart.jpg'
  6.                 ]
  7.  
  8.     arcfile_name = r'D:\Miscellaneous\zipped_files.zip'
  9.  
  10.     if makeArchive(fileList, arcfile_name):
  11.         print arcfile_name, "was created.\n"
  12.         # check the new archive file
  13.         f = zipfile.ZipFile(arcfile_name, 'r')
  14.         for info in f.infolist():
  15.             print info.filename, info.date_time, info.file_size, info.compress_size
  16.         f.close()
  17.     else:
  18.         print "There was an error"
Output:
Expand|Select|Wrap|Line Numbers
  1. >>> archiving file D:\Miscellaneous\Toll Plaza Iso1.bmp
  2. archiving file D:\Miscellaneous\Io_Volcano_Plume.jpg
  3. archiving file D:\Miscellaneous\Dart.jpg
  4. D:\Miscellaneous\zipped_files.zip was created.
  5.  
  6. D:/Miscellaneous/Toll Plaza Iso1.bmp (2001, 2, 1, 5, 8, 2) 5224250 130217
  7. D:/Miscellaneous/Io_Volcano_Plume.jpg (2007, 5, 1, 20, 43, 46) 102987 80937
  8. D:/Miscellaneous/Dart.jpg (2006, 7, 6, 12, 18, 20) 3506067 3060813
Oct 11 '08 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

0
1174
by: Colin Brown | last post by:
As I am getting a larger collection of python program packages the idea of saving them as zips is becoming increasingly attractive. The latest idea is to launch them from a generic wrapper listed below. I have chosen to set the default directory to the location of the zipfile because I usually have an associated configuration inifile alongside. Periodically the topic of program protection crops up. Some zip applications allow password...
3
7583
by: Thiko | last post by:
Hi I take one nightly full database backup at 02:00 and backup the transaction log to one backup set every 15mins. The commands to do this are as follows and are set up to run as database jobs: -- Database Backup BACKUP DATABASE TO WITH NOINIT ,
6
3351
by: Eric Herber | last post by:
I've a question regarding db2 (V8.1) and database backups going to a storage manager like TSM for example. As I can see in the storage manager if I backup the complete database over the TSM API (no tablespace backups) the backup images is stored as a single backup object. Later I will be able to restore the complete database from this image and I will also be able to restore single tablespaces from this backup image as long as I...
1
4767
by: alex | last post by:
Hi ! I couldn't make backups with our new system using db2 8.2. Every time I trigger a backup I get this error message: BACKUP DATABASE EBUERO2 ONLINE TO "/raid/backup/ebuero2/part1", "/raid/backup/ebuero2/part10", "/raid/backup/ebuero2/part11", "/raid/backup/ebuero2/part12", "/raid/backup/ebuero2/part13", "/raid/backup/ebuero2/part14", "/raid/backup/ebuero2/part15", "/raid/backup/ebuero2/part16", "/raid/backup/ebuero2/part17",
4
2647
by: DMTman | last post by:
Who can help me to create a backup strategy that will copy the backend.mdb into separate folders representing either the time, or just folders that are sequentially numbered. I need this for rollback purposes.
6
1552
by: Brian Henry | last post by:
I need to be able to enter a zip code and say show me all the zip codes or towns within X number of miles from that entered one... does anyone know of a soultion or product that can do this? (can even be $ for the product, a free example on how to do it would be nice through to learn from) thanks!
0
1185
by: gardnern | last post by:
I can get PHP to open zip files no problem, however the zips I need to open are password protected. Id like to refrain from calling system commands (system(); or exec(); or passthrough();). Anyone know a solution to this? Thanks.
1
3136
by: m3zmeriz3d | last post by:
i typed a function to enter data into a file to be recalled later, now i have done something here and as soon as this function begins it skips the first 'zips' getline and makes it a blank space and goes directly to 'city' - someone please tell me what the hell happenned here - g'day - mark void addData() { string zips = ""; string city = ""; ofstream outFile;
0
826
by: kinnu | last post by:
Hi, Please help me in source code to download which zips and extracts the files from/to the destination...
0
9976
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9815
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11215
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10802
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10908
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10451
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
8008
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6035
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3267
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.