I have two versions of similar code, one works, the other doesn't:
version 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)
version 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)
When executing the version 2 code, I got an error which says that the file is not open. I got confused because obviously the code is still in the with statement. Does the file get closed automatically right after the f.writelines() method?
f.writelines(new_lines)will replace the entire contents of the file withnew_lines. Is this what you want?