Reputation: 41
I want to read line by line a txt file and save it to a list, my python version is 2.5, but I get syntax error, can you help me? My code is as follows:
with open("test.txt") as f:
content = f.read().splitlines()
Upvotes: 3
Views: 1752
Reputation: 140266
context managers were introduced in python 2.6 (PEP 343). In python 2.5 you have to do:
f = open("test.txt")
content = f.read().splitlines()
f.close()
the main drawback is that you have to remember to close the file
another possibility (maybe even better) is to use __future__
(make it the first line of your script):
from __future__ import with_statement
then you're good to use with
in python 2.5
Upvotes: 5