rocker_raj
rocker_raj

Reputation: 157

Append to a file after nth byte in python

I need to append to the file after nth byte without deleting the previous content.

For Example, If I have a file containing : "Hello World"
and I seek to position(5) to write " this" I should get
"Hello this world"

Is there any mode in which I should open the file??

Currently my code replace the characters
and gives "Hello thisd"

>>> f = open("1.in",'rw+')
>>> f.seek(5)
>>> f.write(' this')
>>> f.close()

any suggestions?

Upvotes: 1

Views: 2664

Answers (3)

dawg
dawg

Reputation: 103774

You can use mmap to do something like this:

import mmap

with open('hello.txt', 'w') as f:
    # create a test file
    f.write('Hello World')

with open('hello.txt','r+') as f:
    # insert 'this' into that 
    mm=mmap.mmap(f.fileno(),0)
    print mm[:]
    idx=mm.find('World')
    f.write(mm[0:idx]+'this '+mm[idx:])

with open('hello.txt','r') as f:  
    # display the test file  
    print f.read()
    # prints 'Hello this World'

mmap allows you to treat a like a mutable string. It has limitation though, such as the slice assignment must be the same as the length. You can use regexs on the mmap objects.

Bottom line, to insert a string into a file stream, you need to read it, insert the string into the read data, and write it back.

Upvotes: 1

Paulo Bu
Paulo Bu

Reputation: 29794

There's no way you can insert in a file. What's normally done is:

  1. Have two buffers, the old file and the new one you'll be adding content
  2. Copy from old to new until the point you want to insert new content
  3. Insert new content in the new file
  4. Continue writing from the old buffer into the new one
  5. (Optional) replace the old file for the new one.

In python it should be something like this:

nth_byte = 5
with open('old_file_path', 'r') as old_buffer, open('new_file_path', 'w') as new_buffer:
    # copy until nth byte
    new_buffer.write(old_buffer.read(nth_byte))
    # insert new content
    new_buffer.write('this')
    # copy the rest of the file
    new_buffer.write(old_buffer.read())

Now you must have Hello this world in new_buffer. After that, is up to you to decide if you overwrite the old with the new or whatever you want to do with it.

Hope this helps!

Upvotes: 6

Amanda
Amanda

Reputation: 12747

I think what you want to do is read the file, break it into two chunks and then rewrite it. Something like:

n = 5
new_string = 'some injection'

with open('example.txt','rw+') as f:
    content = str(f.readlines()[0])
    total_len = len(content)
    one = content[:n]
    three = content[n+1:total_len]
    f.write(one + new_string + three)

Upvotes: 1

Related Questions