Closing files

Henrik Holm news+0409 at henrikholm.com
Sun Nov 28 19:59:31 EST 2004


I have recently started playing around with Python.  Some of the things
I have done have involved reading files.  The way I do this is along the
lines of

  f = file('file.txt')
  lines = f.readlines()
  f.close()

I have noticed that it is possible to do this in one line:

  lines = file('file.txt').readlines()

My question is: does the file get closed if I do the reading in this
manner?

Similarly, for reading the output from other programs or system
commands, I would do:

  o = popen('executable')
  lines = o.readlines()
  o.close()

Is it OK to do this with a one-liner as well, with

  lines = popen('executable').readlines()

without closing the file object?

Thanks,
Henrik Holm



More information about the Python-list mailing list