我有两个版本的类似代码,一个有效,另一个无效:
版本 1
#some code
with open('file', 'w') as f:
f.writelines(new_lines)
with open('file') as f:
i = 0
for line in f:
i = i + 1
if i != 5 and i != 18 and i != 27:
row.append(line)
第 2 版
# some code
with open('file', 'w') as f:
f.writelines(new_lines)
i = 0
for line in f:
i = i + 1
if i != 5 and i != 18 and i != 27:
row.append(line)
执行版本 2 代码时,我收到一条错误消息,指出文件未打开。我很困惑,因为显然代码仍在with
语句中。在 f.writelines() 方法之后文件是否会自动关闭?