如何使用“打开”打开多个文件?在Python中? [英] How can I open multiple files using "with open" in Python?

查看:208
本文介绍了如何使用“打开”打开多个文件?在Python中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时更改几个文件, iff 我可以写入所有文件。我想知道是否可以将多个打开的调用与和语句结合在一起:

I want to change a couple of files at one time, iff I can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the with statement:

try:
  with open('a', 'w') as a and open('b', 'w') as b:
    do_something()
except IOError as e:
  print 'Operation failed: %s' % e.strerror

这是不可能的,这个问题的一个优雅的解决方案是什么样子?

If that's not possible, what would an elegant solution to this problem look like?

推荐答案

从Python 2.7(或3.1分别)可以用open('a','w')作为a,open('b','w')来写

As of Python 2.7 (or 3.1 respectively) you can write

with open('a', 'w') as a, open('b', 'w') as b:
    do_something()

在早期版本的Python中,有时可以使用
contextlib.nested() 来嵌套上下文管理器。这不会像预期打开多个文件一样工作 - 请参阅链接的文档的详细信息。

In earlier versions of Python, you can sometimes use contextlib.nested() to nest context managers. This won't work as expected for opening multiples files, though -- see the linked documentation for details.

这篇关于如何使用“打开”打开多个文件?在Python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆