Search code examples
pythontarfile

Get python tarfile to skip files without read permission


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

Solution

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