You have to be very careful when modifying a file in-place like that. The modified text has to be exactly the same size as the original text, or you'll make a mess. The following bytes in the file won't magically move if the replacement text is the wrong size.
But without seeing your data it's not possible to tell if that's a problem or not with your code.
However, your code isn't writing the new text in the correct location, and that is a problem. You can't just write the new text at the current location, you need to seek()
to the correct position. The code below show two slightly different ways to deal with that. It can be done in a for line in f:
loop, but I think it's somewhat cleaner to do it with a simple while True:
loop.
#!/usr/bin/env python
""" Inplace file update demo
Written by PM 2Ring 2015.08.20
See http://stackoverflow.com/q/32096531/4014959
"""
def create(fname):
data = 'zero one two three four five six seven eight nine'
with open(fname, 'w') as f:
for s in data.split():
f.write(s + '\n')
def modify0(fname):
with open(fname, 'r+') as f:
fpos = 0
for line in f:
print repr(line)
outline = line[:2].upper() + line[2:]
f.seek(fpos)
f.write(outline)
fpos += len(line)
f.seek(fpos)
def modify1(fname):
with open(fname, 'r+') as f:
while True:
fprev = f.tell()
line = f.readline()
if not line:
break
print repr(line)
f.seek(fprev)
outline = line[:2].upper() + line[2:]
f.write(outline)
def show(fname):
with open(fname, 'r') as f:
for line in f:
print repr(line)
modify = modify1
fname = 'testfile.txt'
create(fname)
modify(fname)
print '\n' + 20*' - ' + '\n'
show(fname)
output
'zero\n'
'one\n'
'two\n'
'three\n'
'four\n'
'five\n'
'six\n'
'seven\n'
'eight\n'
'nine\n'
- - - - - - - - - - - - - - - - - - - -
'ZEro\n'
'ONe\n'
'TWo\n'
'THree\n'
'FOur\n'
'FIve\n'
'SIx\n'
'SEven\n'
'EIght\n'
'NIne\n'