【问题标题】:Opening two files simultaneously on a "with" context [duplicate]在“with”上下文中同时打开两个文件[重复]
【发布时间】:2019-10-06 16:21:00
【问题描述】:

我想知道 Python 3 中是否存在允许我在同一个 with 上下文中打开两个(或更多)文件的结构。

我正在寻找的是这样的:

from pathlib import Path

file1 = Path('file1.txt')
file2 = Path('file2.txt')

with file1.open() as f1 and file2.open() as f2:
    '''do something with file handles...

上面的代码显然是无效的,这就引出了这个问题。

【问题讨论】:

  • 试试and,

标签: python python-3.x with-statement


【解决方案1】:

使用逗号:

from pathlib import Path

file1 = Path('file1.txt')
file2 = Path('file2.txt')

with file1.open() as f1, file2.open() as f2:
    '''do something with file handles...

Documentation for with statement 涵盖了多个上下文表达式的情况。

【讨论】:

  • 谢谢,@sanyash。向我指出文档的额外奖励。 :-)
【解决方案2】:

正确的是with file1.open() as f1, file2.open() as f2:

根据你想用f1f2做什么,你可以直接使用 pathlib.Path.read_text()pathlib.Path.write_text(),例如

from pathlib import Path

file1 = Path('file1.txt')
content = file1.read_text()
print(content)

【讨论】:

  • 谢谢。我习惯了pathlib.Path() 方法。我的兴趣在于with 上下文。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-25
  • 1970-01-01
  • 2015-02-13
  • 2016-07-31
相关资源
最近更新 更多