2010-05-20 56 views
1

我正在尝试编写一个函数,该文件在Windows XP上备份一个具有不同权限的文件的目录。我正在使用tarfile模块来对目录进行tar。目前只要程序遇到没有读取权限的文件,就会停止提供错误:IOError:[Errno 13]权限被拒绝:'文件路径'。我希望它跳过它无法读取的文件,而不是结束tar操作。这是我现在使用的代码:获取python tarfile跳过没有读取权限的文件

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

回答

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 

[编辑]作为Tarfile.add默认是递归的,添加目录时,我已经添加了recursive=False参数,否则你可能会遇到的问题。

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 
0

我想补充一下其他人说,有哪个可以传递文件参数和你正在寻找以检查属性的属性原来的Python功能:hasattr('/path/to/file.txt', "read")hasattr('/path/to/file.txt', "write")等 希望这帮助那里的其他人