I can go in to the file and read the line using enumerate
but I can't figure out how to change the line.
The fileinput
method overwrites the file and the append method in open()
will only append to the end of the file.
I want to append and overwrite to only a certain line in the file while keeping the rest of the file intact.
with open('test2.py', 'r+') as f:
for i, line in enumerate(f):
if i == 4:
if line != '2':
line = '2'
f.write(line)
print line
I don't get any errors in the code above it just prints '2'
in the terminal but it doesn't change the line of text in test2.py
to '2'
.
test2.py will be
#
#
#
'''
4
'''
#
I need to change 4 to 2