gpt4 book ai didi

python - python 3.7 中的 tarfile 过滤器

转载 作者:行者123 更新时间:2023-12-01 01:39:51 25 4
gpt4 key购买 nike

这是我分离出来进行测试的备份脚本的一部分。这曾经在 python 3.6 中工作,但在 python 3.7 中遇到错误。我检查了文档,但无法真正弄清楚发生了什么变化。

#! /usr/bin/python

import os
import tarfile
import arrow


stmp = arrow.now().format('YYYY-MM-DD')
backup_path = "/home/akya/playground/"

###########################################################
# Functions
###########################################################

def exclude_function(filename):
if filename in exclude_files or os.path.splitext(filename)[1] in exclude_files:
return True
else:
return False

def compress():
with tarfile.open(myfile, "w:gz") as tar:
for name in L:
tar.add(name, filter=exclude_function)

path1 = "/home/akya/playground/test"
backup_name = "test-"

L = [path1]
exclude_files = [".sh", ".html", ".json", "/home/akya/playground/test/.git"]
myfile = str(backup_path + backup_name + stmp + ".tar.gz")

compress()

我希望 tarfile 排除排除文件中的任何扩展名和路径。这就是我得到的

Traceback (most recent call last):
File "exec.py", line 33, in <module>
compress()
File "exec.py", line 24, in compress
tar.add(name, filter=exclude_function)
File "/usr/lib/python3.7/tarfile.py", line 1934, in add
tarinfo = filter(tarinfo)
File "exec.py", line 16, in exclude_function
if filename in exclude_files or os.path.splitext(filename)[1] in exclude_files:
File "/usr/lib/python3.7/posixpath.py", line 122, in splitext
p = os.fspath(p)
TypeError: expected str, bytes or os.PathLike object, not TarInfo

谁能指出需要进行的更改吗?或者更好的使用过滤器的方法?

最佳答案

filter 回调传递 TarInfo结构到您的回调,因此您可以按名称以外的其他内容进行过滤:日期、大小、修改时间(看起来非常像 stat 对象)...

此外,它不能以这种方式工作(返回 bool 值),如果您想排除此条目,则必须返回 None:

TarFile.add(name, arcname=None, recursive=True, *, filter=None)

... If filter is given, it should be a function that takes a TarInfo object argument and returns the changed TarInfo object. If it instead returns None the TarInfo object will be excluded from the archive. See Examples for an example.

在您的情况下,只需选择 .name 字段,如果与您的过滤器匹配,则返回 None 。否则返回您收到的相同 tarinfo 结构。

def exclude_function(tarinfo):
filename = tarinfo.name
return None if filename in exclude_files or os.path.splitext(filename)[1] in exclude_files else tarinfo

(请注意,我不知道为什么它在早期版本中对您有用,也许您在 except_files 部分中添加了 或 os.path.splitext(filename)[1] ,这表明类型不正确 - 即使使用错误类型的对象,第一个 in 测试也不会崩溃 - 但这是正确的方法)

关于python - python 3.7 中的 tarfile 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51998344/

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