文件在达到末尾之前已关闭 - 使用Python中的Exitstack

发布于 2025-02-03 20:03:36 字数 482 浏览 2 评论 0原文

我已经使用以下代码同时读取多个文件

from contextlib import ExitStack

files_to_parse = [file1, file2, file3]
    
with ExitStack() as stack:
    files = [stack.enter_context(open(i, "r")) for i in files_to_parse]
    for rows in zip(*files):
        for r in rows:
            #do stuff
        

,但是我注意到,由于我所有的文件都没有相同数量的行,只要最短文件到达末尾,所有文件都会关闭。

我使用了上面的代码(在Stackoverflow上找到了它),因为我需要同时解析几个文件(以节省时间)。这样做,将计算时间除以4。但是,所有文件并非完全是因为我上面提到的问题。

有什么方法可以解决这个问题吗?

I have used the following code to read multiple files simultaneously

from contextlib import ExitStack

files_to_parse = [file1, file2, file3]
    
with ExitStack() as stack:
    files = [stack.enter_context(open(i, "r")) for i in files_to_parse]
    for rows in zip(*files):
        for r in rows:
            #do stuff
        

However I have noticed that since all my files don't have the same number of lines, whenever the shortest file reaches the end, all the files will close.

I used the code above (which I found here on stackoverflow) because I need to parse several files at the same time (to save time). Doing so, divide the computing time by 4. However all files aren't parsed entirely because of the problem I have mentioned above.

Is there any way to solve this problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久光 2025-02-10 20:03:36

open 可以用作上下文管理器,但不必。您可能会以古老的方式使用它,在这里您负责关闭,也就是说

try:
    files = [open(fname) for fname in filenames]
    # here do what you need to with files
finally:
    for file in files:
        file.close()

open might be used as context manager, but does not have to. You might use it in ancient way, where you take responsibility to close it, that is

try:
    files = [open(fname) for fname in filenames]
    # here do what you need to with files
finally:
    for file in files:
        file.close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文