Sara Ebrahimi
Sara Ebrahimi

Reputation: 41

Read a txt file in python 2.5

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

Answers (1)

Jean-François Fabre
Jean-François Fabre

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

Related Questions