文件在达到末尾之前已关闭 - 使用Python中的Exitstack
我已经使用以下代码同时读取多个文件
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
open 可以用作上下文管理器,但不必。您可能会以古老的方式使用它,在这里您负责
关闭
,也就是说open
might be used as context manager, but does not have to. You might use it in ancient way, where you take responsibility toclose
it, that is