Search code examples
pythonio

Python - Can I update my file using Insert mode?


Basically I want to insert text with overwriting other text, like when you click "Insert" button on your keyboard. Is that possible? I really don't want to read all of the lines, I just want to change one letter.

File before:

abcd

Code:

with open(file, INSERT) as f:
    f.seek(1)
    f.write('e')

File after:

aecd

Solution

  • If you want to do exactly what you are saying, this should do the trick:

    with open(file, 'r+') as f:
        f.seek(1)
        f.write('e')
    

    Output:

    aecd