我想逐行读取一个txt文件并将其保存到一个列表中,我的python版本是2.5,但出现语法错误,你能帮我吗?我的代码如下:
with open("test.txt") as f:
content = f.read().splitlines()
Run Code Online (Sandbox Code Playgroud)
上下文管理器是在 python 2.6 ( PEP 343 )中引入的。在 python 2.5 中,您必须执行以下操作:
f = open("test.txt")
content = f.read().splitlines()
f.close()
Run Code Online (Sandbox Code Playgroud)
主要缺点是你必须记住关闭文件
另一种可能性(也许更好)是使用__future__(使其成为脚本的第一行):
from __future__ import with_statement
Run Code Online (Sandbox Code Playgroud)
那么你很适合with在 python 2.5 中使用