1

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?

4

3 回答 3

6

你没有办法insert在文件中。通常做的是:

  1. 有两个缓冲区,旧文件和要添加内容的新文件
  2. 从旧复制到新直到要插入新内容的点
  3. 在新文件中插入新内容
  4. 继续从旧缓冲区写入新缓冲区
  5. (可选)将旧文件替换为新文件。

在python中它应该是这样的:

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())

现在你必须Hello this worldnew_buffer. 之后,由你决定是用新的覆盖旧的还是你想用它做什么。

希望这可以帮助!

于 2013-09-16T23:34:01.127 回答
1

我认为您要做的是读取文件,将其分成两块,然后重写。就像是:

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)
于 2013-09-16T23:37:37.583 回答
1

您可以使用mmap执行以下操作:

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允许您将 a 视为可变字符串。但它有限制,例如切片分配必须与长度相同。您可以在 mmap 对象上使用正则表达式。

底线,要将字符串插入文件流,您需要读取它,将字符串插入到读取的数据中,然后将其写回。

于 2013-09-17T06:26:51.110 回答