8

How do I close a file in python after opening it this way:

line = open("file.txt", "r").readlines()[7]

Milo Wielondek
  • 4,164
  • 3
  • 33
  • 45
  • check out this answer http://stackoverflow.com/questions/4599980/python-close-file-descriptor-question – unni Oct 28 '11 at 10:15
  • 2
    You don't. You let Python close it for you, either during garbage collection or when the program ends. Usually this is not a problem which is why many code examples in the Python docs do it this way. – Tim Pietzcker Oct 28 '11 at 10:17
  • 5
    @Tim Pietzcker: In CPython you can depend on reference counting, but it's an implementation detail that won't work in other implementations such as PyPy or Jython. In that case opening too many files could exhaust the available file descriptors. – Eryk Sun Oct 28 '11 at 10:25
  • 2
    @eryksun: No you can't depend on it! Your file object may be part of a reference cycle in which case it won't be destroyed when the binding goes out of scope. Then it will live on until the cyclical garbage collector takes care of it which may be a long time in the future. – Björn Lindqvist Oct 28 '11 at 14:13

2 Answers2

4

Best to use a context manager. This will close the file automatically at the end of the block and doesn't rely on implementation details of the garbarge collection

with open("file.txt", "r") as f:
    line = f.readlines()[7]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 3
    What @Tim Pietzcker wrote below. I'm aware of this method, however I was wondering whether there's another way around this, as I mentioned in the title, without assigning the file instance a variable. – Milo Wielondek Oct 28 '11 at 12:27
0

There are several ways, e.g you could just use f = open(...) and del f.

If your Python version supports it you can also use the with statement:

with open("file.txt", "r") as f:
    line = f.readlines()[7]

This automatically closes your file.

EDIT: I don't get why I'm downvoted for explaining how to create a correct way to deal with files. Maybe "without assigning a variable" is just not preferable.

Constantinius
  • 34,183
  • 8
  • 77
  • 85