Home > other >  Python - Can I update my file using Insert mode?
Python - Can I update my file using Insert mode?

Time:01-19

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

CodePudding user response:

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

CodePudding user response:

I found an answer to a similar question from way back. Here is an updated version of the answer I found (tailored for your needs):

import os,mmap

with open("test", "r b") as f:
     mm = mmap.mmap(f.fileno(), 0)
     mm[1:2] = b"e"
     mm.close()

Output

aecd

mmap documentaion has a similar example

  •  Tags:  
  • Related