Backup with zips

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Bouzy
    New Member
    • Jun 2007
    • 30

    Backup with zips

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

    Code:
    #!/usr/bin/python
    # Filename: backup_zip.py
    
    import os
    import zipfile
    import glob
    
    r = 1
    
    def backup():
    
       cwd = os.getcwd()
    
       # for file in os.walk(cwd):
       for dirpath, dirs, files in os.walk(cwd):
          z_path = os.path.join(dirpath,file) 
       #   docs = open(file, 'r')
          docs = open(z_path, 'r')
          output = zipfile.ZipFile(docs, 'w')
          output.write(docs)
    
       output.close()
    
      # Ignore old code I was messing with \\\\\\\
      # ZipFile(cwd['w'[ZIP_STORED[allowZip64]]]):
      #   z_path = os.path.join(dirpath,file)
      #   start = cwd.rfind(
      #   output.write(z_path,z_path[start:])
      #
      # if file == '*.zip':
      #     
      # else:
      #   output.write(z_path)
      # output.close()
      #
      # output_append.write(z_path)
    
    while r == 1:
    
       print "This script when run backs up files in a directory by comressing them to zips. "
       begin = raw_input("Do you wish to back up files in this directory [type: yes or no] ")   
    
       if begin == "yes":
          r = 1
          
          backup()
       elif begin == "no":
          r = 0
       else:
          print "Enter yes or no"
    It is giving me this error..

    Code:
        z_path = os.path.join(dirpath,file)
      File "C:\Python25\lib\ntpath.py", line 67, in join
        elif isabs(b):
      File "C:\Python25\lib\ntpath.py", line 53, in isabs
        s = splitdrive(s)[1]
      File "C:\Python25\lib\ntpath.py", line 119, in splitdrive
        if p[1:2] == ':':
    TypeError: 'type' object is unsubscriptable
    I got this part from another script I saw..

    Code:
    for dirpath, dirs, files in os.walk(cwd):
          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.
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    You are trying to join the path and the Python built-in file.
    Code:
    >>> file
    <type 'file'>
    >>> type(file)
    <type 'type'>
    >>> help(file)
    Help on class file in module __builtin__:
    
    class file(object)
     |  file(name[, mode[, buffering]]) -> file object
     |  
     |  Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      How would ZipFile() find the files if you don't give it the full path? Here's an example:[code=Python]import zipfile, os

      def makeArchive(fil eList, archive):
      """
      'fileList' is a list of file names - full path each name
      'archive' is the file name for the archive with a full path
      """
      try:
      # ZipFile will accept a file name or file object
      a = zipfile.ZipFile (archive, 'w', zipfile.ZIP_DEF LATED)
      for f in fileList:
      print "archiving file %s" % (f)
      a.write(f) # (f, os.path.basenam e(f))
      a.close()
      return True
      except: return False[/code]

      Comment

      • Bouzy
        New Member
        • Jun 2007
        • 30

        #4
        When I run your code it doesn't give any errors. However, it doesn't work. When I run this as my code...

        Code:
        #!/usr/bin/python
        # Filename: backup_zip.py
        
        import os, zipfile
        
        r = 1
        
        while r == 1:
        
           print "This script when run backs up files in a directory by comressing them to zips. "
           begin = raw_input("Do you wish to back up files in this directory [type: yes or no] ")   
        
           if begin == "yes":
              r = 1
              backup()  
           elif begin == "no":
              r = 0
           else:
              print "Enter yes or no"
        
        def backup(fileList, archive):
        
           cwd = os.getcwd()
        #   archive = os.pathname
        #   fileList = dirpath, dirs, files in os.walk(cwd)
           f = os.path.basename
        
           output = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
        
           for f in fileList:
              print "archiving file '%s'" % (f)
              output.write(f)
           output.close()
         
        if __name__ == "__main__":
           backup()
        it gives me this error...

        Code:
        Traceback (most recent call last):
          File "C:\Documents and Settings\Gabe\Desktop\test\backup_zip.py", line 15, in <module>
            backup()
        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..

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          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:
          Code:
          if __name__== '__main__':
          
              fileList = [r'D:\Miscellaneous\Toll Plaza Iso1.bmp',
                          r'D:\Miscellaneous\Io_Volcano_Plume.jpg',
                          r'D:\Miscellaneous\Dart.jpg'
                          ]
          
              arcfile_name = r'D:\Miscellaneous\zipped_files.zip'
          
              if makeArchive(fileList, arcfile_name):
                  print arcfile_name, "was created.\n"
                  # check the new archive file
                  f = zipfile.ZipFile(arcfile_name, 'r')
                  for info in f.infolist():
                      print info.filename, info.date_time, info.file_size, info.compress_size
                  f.close()
              else:
                  print "There was an error"
          Output:[code=Python]>>> archiving file D:\Miscellaneou s\Toll Plaza Iso1.bmp
          archiving file D:\Miscellaneou s\Io_Volcano_Pl ume.jpg
          archiving file D:\Miscellaneou s\Dart.jpg
          D:\Miscellaneou s\zipped_files. zip was created.

          D:/Miscellaneous/Toll Plaza Iso1.bmp (2001, 2, 1, 5, 8, 2) 5224250 130217
          D:/Miscellaneous/Io_Volcano_Plum e.jpg (2007, 5, 1, 20, 43, 46) 102987 80937
          D:/Miscellaneous/Dart.jpg (2006, 7, 6, 12, 18, 20) 3506067 3060813[/code]

          Comment

          Working...