tags:

views:

54

answers:

2

I'm trying to write a function that backs up a directory with files of different permission to an archive on Windows XP. I'm using the tarfile module to tar the directory. Currently as soon as the program encounters a file that does not have read permissions, it stops giving the error: IOError: [Errno 13] Permission denied: 'path to file'. I would like it to instead just skip over the files it cannot read rather than end the tar operation. This is the code I am using now:

def compressTar():
 """Build and gzip the tar archive."""
 folder = 'C:\\Documents and Settings'
 tar = tarfile.open ("C:\\WINDOWS\\Program\\archive.tar.gz", "w:gz")

 try:
  print "Attempting to build a backup archive"
  tar.add(folder)
 except:
  print "Permission denied attempting to create a backup archive"
  print "Building a limited archive conatining files with read permissions."

  for root, dirs, files in os.walk(folder):
   for f in files:
    tar.add(os.path.join(root, f))
   for d in dirs:
    tar.add(os.path.join(root, d))
+1  A: 

You will need the same try/except blocks for when you are trying to add the files with read permissions. Right now, if any of the files or sub directories are not readable, then your program will crash.

Another option that isn't so reliant on try blocks is to check the permissions before trying to add the file/folder to your tarball. There is a whole question about how to best do this (and some pitfalls to avoid when using Windows): http://stackoverflow.com/questions/539133/python-test-directory-permissions

The basic pseudo code would be something like:

if folder has read permissions:
    add folder to tarball
else:
    for each item in folder:
        if item has read permission:
            add item to tarball
swanson
+1  A: 

You should add more try statements :

for root, dirs, files in os.walk(folder):
    for f in files:
      try:
        tar.add(os.path.join(root, f))
      except IOError:
        pass
    for d in dirs:
      try:
        tar.add(os.path.join(root, d), recursive=False)
      except IOError:
        pass

[edit] As Tarfile.add is recursive by default, I've added the recursive=False parameter when adding directories, otherwise you could run into problems.

stanlekub