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

如何嵌套任意数量的Python文件上下文管理器?,第1张

概述我想采用任意数量的路径来表示嵌套的tar档案,并对最里面的档案执行 *** 作.问题是,嵌套可以是任意的,因此我需要的上下文管理器的数量也是任意的.举个例子:ARCHIVE_PATH = 'path/to/archive.tar' INNER_PATHS = ( 'nested/within/archive/one.tar', 'nested/wi

我想采用任意数量的路径来表示嵌套的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",# 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文件上下文管理器?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1205332.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存