获取python tarfile以跳过没有读取权限的文件

时间:2010-05-20 18:02:00

标签: python tarfile

我正在尝试编写一个函数来备份具有不同权限的文件的目录到Windows XP上的存档。我正在使用tarfile模块来tar目录。目前,一旦程序遇到没有读取权限的文件,它就会停止给出错误:IOError:[Errno 13] Permission denied:'path to file'。我希望它只是跳过它无法读取的文件,而不是结束tar操作。这是我现在使用的代码:

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

3 个答案:

答案 0 :(得分:2)

您应该添加更多try语句:

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]由于默认情况下Tarfile.add是递归的,我在添加目录时添加了recursive=False参数,否则可能会遇到问题。

答案 1 :(得分:1)

当您尝试添加具有读取权限的文件时,您将需要相同的try / except块。现在,如果任何文件或子目录不可读,那么您的程序将崩溃。

另一个不依赖try块的选项是在尝试将文件/文件夹添加到tarball之前检​​查权限。关于如何最好地做到这一点有一个完整的问题(以及使用Windows时要避免的一些陷阱):Python - Test directory permissions

基本的伪代码类似于:

if folder has read permissions:
    add folder to tarball
else:
    for each item in folder:
        if item has read permission:
            add item to tarball

答案 2 :(得分:0)

只是为了添加其他人所说的内容,有一个本机python函数,你可以传递file参数和你要查找的属性来检查该属性:hasattr('/path/to/file.txt', "read")或{{1} } 等等 希望这有助于其他任何人

相关问题