python - 是否可以在 python 中使用可选的 with/as 语句?

标签 python file-io with-statement

取而代之的是:

FILE = open(f)
do_something(FILE)
FILE.close()

最好用这个:

with open(f) as FILE:
    do_something(FILE)

如果我有这样的事情怎么办?

if f is not None:
   FILE = open(f)
else:
   FILE = None
do_something(FILE)
if FILE is not None:
    FILE.close()

do_something 也有一个“if FILE is None”子句,并且在那种情况下仍然做一些有用的事情 - 我不想如果 FILE 是 None 就跳过 do_something。

有没有一种合理的方法可以将其转换为 with/as 形式?或者我只是想以错误的方式解决可选文件问题?

最佳答案

如果你只是这样写:

if f is not None:
    with open(f) as FILE:
        do_something(FILE)
else:
    do_something(f)

(file 是内置 btw)

更新

这是一种使用不会崩溃的可选 None 来执行即时上下文的时髦方法:

from contextlib import contextmanager

none_context = contextmanager(lambda: iter([None]))()
# <contextlib.GeneratorContextManager at 0x1021a0110>

with (open(f) if f is not None else none_context) as FILE:
    do_something(FILE)

它创建一个返回 None 值的上下文。 with 将生成 FILE 作为文件对象,或者生成 None 类型。但是 None 类型将有一个适当的 __exit__

更新

如果您使用的是 Python 3.7 或更高版本,那么您可以以更简单的方式声明空上下文管理器以用于替代目的:

import contextlib
none_context = contextlib.nullcontext()

您可以在这里阅读更多相关信息:

https://docs.python.org/3.7/library/contextlib.html#contextlib.nullcontext

关于python - 是否可以在 python 中使用可选的 with/as 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12168208/

相关文章:

Python,理解霍夫曼代码

vb.net - With... End With vs Using in VB.NET

c - C 文件 I/O 中的段错误

c - 使用结构读取文件时出现问题

excel - Delphi 7 with..do 语句不适用于变体变量

vb.net - 在 vb.net 中是否有类似于 "with"的东西,但对于函数?

python - 在asyncio中使用run_in_executor时,事件循环是否在主线程中执行?

python - 根据值向网格图添加边框

python - 在 python 中导出一个 utf-8 csv 文件

python - 对不同文件中的列进行操作