If you are in fact looking to overwrite the file line by line, you'll have to do some additional work - since the only modes available are r
ead ,w
rite and a
ppend, neither of which actually do a line-by-line overwrite.
See if this is what you're looking for:
# Write some data to the file first.
with open('file.txt', 'w') as f:
for s in ['This\n', `is a\n`, `test\n`]:
f.write(s)
# The file now looks like this:
# file.txt
# >This
# >is a
# >test
# Now overwrite
new_lines = ['Some\n', 'New data\n']
with open('file.txt', 'a') as f:
# Get the previous contents
lines = f.readlines()
# Overwrite
for i in range(len(new_lines)):
f.write(new_lines[i])
if len(lines) > len(new_lines):
for i in range(len(new_lines), len(lines)):
f.write(lines[i])
As you can see, you first need to 'save' the contents of the file in a buffer (lines
), and then replace that.
The reason for that is how the file modes work.