0

I am counting the lines in a file using the following:

n = sum(1 for line in open(counts_file_location))

Questions:

  1. does the file counts_file_location gets closed automatically at the end of "for" loop?
  2. if the file does not get closed automatically, how do I close it? There is no file_pointer assigned to to the file.
Patrick Kostjens
  • 5,065
  • 6
  • 29
  • 46
sermolin
  • 161
  • 1
  • 2
  • 6
  • 2
    Possible duplicate of [Is explicitly closing files important?](http://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important) – Patrick Kostjens Mar 10 '17 at 21:44
  • Possible duplicate of [How to get line count cheaply in Python?](http://stackoverflow.com/questions/845058/how-to-get-line-count-cheaply-in-python) – dot.Py Mar 10 '17 at 21:44
  • Just don't open files this way. Use a `with` statement. It's much safer, especially on Python implementations that aren't CPython. – user2357112 Mar 10 '17 at 21:44

3 Answers3

1

It should, but it is implementation dependent

If you want to make sure the file gets closed, try with open:

with open(counts_file_location) as file:
    n = sum(1 for line in file)
Yang
  • 858
  • 6
  • 22
0

Here's a single line to open the file, close the file, and get the number of lines:

lineCount = (lambda a: (sum(1 for line in a), a.close()))(open(counts_file_location))[0]
Neil
  • 14,063
  • 3
  • 30
  • 51
0
count = 0
with open(counts_file_location) as my_file:
  for line in my_file:
    count += 1
print count

It's not a one-liner, but it's readable, works fine and closes the file.

If you need it often, you could define the corresponding function.

Eric Duminil
  • 52,989
  • 9
  • 71
  • 124