If I have to deal with a file many times in a script. Basically if I need to read it at the beginning of my script, and write it at the end. Is it better to do:
f = open("myfile", "r")
lines = f.readlines()
f.close()
# ...
# Edit some lines
# ...
f = open("myfile", "w")
f.write(lines)
f.close()
Or:
f = open("myfile", "r+")
lines = f.readlines()
# ...
# Edit some lines
# ...
f.seek(0)
f.truncate()
f.write(lines)
f.close()
By "better" I mean "more secure". I think that both scripts have a security breach if the process is stopped while the file is still opened, but this has less chances to happen in the former script.
I don't think the languages matters but I mainly use Python.