5

I came across this syntax for reading the lines in a file.

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

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Mike S
  • 1,451
  • 1
  • 16
  • 34

2 Answers2

4

You can write something like

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

but you can't put the with into the list comprehension.

It might be possible to write something like

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

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.

fafl
  • 7,222
  • 3
  • 27
  • 50
1

with uses a function as a context manager, so no. f has no value until inside the block. The best you could do is a 2 line implementation.

Casey Kinsey
  • 1,451
  • 9
  • 16