gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:58:43 25 4
gpt4 key购买 nike

我正在尝试编写一个函数,用于将具有不同权限的文件的目录备份到 Windows XP 上的存档。我正在使用 tarfile 模块来 tar 目录。目前,一旦程序遇到没有读取权限的文件,它就会停止给出错误:IOError:[Errno 13]权限被拒绝:“文件路径”。我希望它只是跳过它无法读取的文件而不是结束 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))

最佳答案

您应该添加更多 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 参数,否则可能会遇到问题。

关于python - 获取 python tarfile 以跳过没有读取权限的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2876517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com