问题描述
我碰到了这种语法,用于读取文件中的行.
I came across this syntax for reading the lines in a file.
with open(...) as f:
for line in f:
<do something with line>
说我希望<do something with line>
行将每行追加到列表中.有什么方法可以使用with
关键字在列表理解中完成此任务吗?或者,至少有某种方法可以在一条语句中完成我想要的事情?
Say I wanted the <do something with line>
line to append each line to a list. Is there any way to accomplish this, using the with
keyword, in a list comprehension? Or, is there at least some way of doing what I want in a single statement?
推荐答案
您可以编写类似
with open(...) as f:
l = [int(line) for line in f]
但是您不能将with
放入列表理解中.
but you can't put the with
into the list comprehension.
也许可以写类似的东西
l = [int(line) for line in open(...).read().split("\n")]
,但是您稍后需要手动调用f.close(),这种方式不会给您变量f.超出范围时,可能会自动关闭filhandle,但我不会依赖它.
but you would need to call f.close() later manually and this way gives you no variable f. It might happen that the filhandle is closed automatically when going out of scope, but I would not rely on it.
这篇关于“具有"列表理解中的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!