8

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

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

4
  • check out this answer stackoverflow.com/questions/4599980/…
    – unni
    Commented Oct 28, 2011 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. Commented Oct 28, 2011 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
    Commented Oct 28, 2011 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. Commented Oct 28, 2011 at 14:13

2 Answers 2

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]
1
  • 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. Commented Oct 28, 2011 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.

1
  • 4
    He explicitly asks how to do it without assigning a variable. Commented Oct 28, 2011 at 10:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.