gpt4 book ai didi

python - 如何嵌套任意数量的 Python 文件上下文管理器?

转载 作者:太空狗 更新时间:2023-10-30 01:16:05 25 4
gpt4 key购买 nike

我想采用代表嵌套 tar 存档的任意数量的路径,并对最里面的存档执行操作。问题是,嵌套可以是任意的,所以我需要的上下文管理器的数量也是任意的。

举个例子:

ARCHIVE_PATH = "path/to/archive.tar"

INNER_PATHS = (
"nested/within/archive/one.tar",
"nested/within/archive/two.tar",
# Arbitary number of these
)

def list_inner_contents(archive_path, inner_paths):
with TarFile(archive_path) as tf1:
with TarFile(fileobj=tf1.extractfile(inner_paths[0])) as tf2:
with TarFile(fileobj=tf2.extractfile(inner_paths[1])) as tf3:
# ...arbitary level of these!
return tfX.getnames()

contents = list_inner_contents(ARCHIVE_PATH, INNER_PATHS))

我不能使用 with 语句的 nesting syntax因为可以嵌套任意数量的级别。我不能使用 contextlib.nested因为文档就在那里说:

...using nested() to open two files is a programming error as the first file will not be closed promptly if an exception is thrown when opening the second file.

有没有一种方法可以使用语言结构来执行此操作,或者我是否需要手动管理我自己的打开文件对象堆栈?

最佳答案

对于这种情况,您可以使用递归。对于这种情况感觉是最自然的(当然如果 Python 中还没有特殊处理的话):

ARCHIVE_PATH = "path/to/archive.tar"

INNER_PATHS = [
"nested/within/archive/one.tar",
"nested/within/archive/two.tar",
# Arbitary number of these
]

def list_inner_contents(archive_path, inner_paths):
def rec(tf, rest_paths):
if not rest_paths:
return tf.getnames()

with TarFile(fileobj=tf.extractfile(rest_paths[0])) as tf2:
return rec(tf2, rest_paths[1:])

with TarFile(archive_path) as tf:
try:
return rec(tf, inner_paths)
except RuntimeError:
# We come here in case the inner_paths list is too long
# and we go too deeply in the recursion
return None

关于python - 如何嵌套任意数量的 Python 文件上下文管理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16259603/

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