简体   繁体   中英

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM