Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a file in python without assigning a variable

Tags:

python

file-io

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

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

like image 450
Milo Wielondek Avatar asked Oct 28 '11 10:10

Milo Wielondek


1 Answers

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]
like image 176
John La Rooy Avatar answered Sep 28 '22 18:09

John La Rooy