python - 列表理解中的 "with"关键字?

标签 python list-comprehension with-statement

<分区>

我遇到了这种用于读取文件中的行的语法。

with open(...) as f:
    for line in f:
        <do something with line>

假设我想要 <do something with line> line 将每一行附加到列表中。有什么办法可以做到这一点,使用 with关键字,在列表理解中?或者,至少有某种方法可以在一条语句中完成我想要的操作吗?

最佳答案

你可以这样写

with open(...) as f:
    l = [int(line) for line in f]

但是您不能将 with 放入列表解析中。

也许可以这样写

l = [int(line) for line in open(...).read().split("\n")]

但是您稍后需要手动调用 f.close() 并且这种方式不会为您提供变量 f。当超出范围时,filhandle 可能会自动关闭,但我不会依赖它。

关于python - 列表理解中的 "with"关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43619143/

相关文章:

python - GetStream (Django) - 无法丰富通知提要

Python - 如何过滤Excel中的数据

python - 在 Pycharm 中的 for 循环内调试列表理解

delphi - 复合 "with"语句中的名称解析如何工作?

python - 在 python 上下文管理器中返回 finally block

python - 机器学习 : Move Treshhold

python - Sublime CodeIntel,添加 django 路径

haskell - Haskell中具有列表理解的集合的Powerset

python - 给定条件递增前 n 个列表元素

python - 上下文管理器的单元测试失败,出现 AttributeError : __exit__