How to seek and append to a binary file in python?

萝らか妹 提交于 2020-01-01 04:45:10

问题


I am having problems appending data to a binary file. When i seek() to a location, then write() at that location and then read the whole file, i find that the data was not written at the location that i wanted. Instead, i find it right after every other data/text.

My code

file = open('myfile.dat', 'wb')
file.write('This is a sample')
file.close()

file = open('myfile.dat', 'ab')
file.seek(5)
file.write(' text')
file.close()

file = open('myfile.dat', 'rb')
print file.read()  # -> This is a sample text

You can see that the seek does not work. How do i resolve this? are there other ways of achieving this?

Thanks


回答1:


On some systems, 'ab' forces all writes to happen at the end of the file. You probably want 'r+b'.




回答2:


r+b should work as you wish




回答3:


Leave out the seek command. You already opened the file for append with 'a'.




回答4:


NOTE : Remember new bytes over write previous bytes

As per python 3 syntax

with open('myfile.dat', 'wb') as file:
    b = bytearray(b'This is a sample')
    file.write(b)

with open('myfile.dat', 'rb+') as file:
    file.seek(5)
    b1 = bytearray(b'  text')
    #remember new bytes over write previous bytes
    file.write(b1)

with open('myfile.dat', 'rb') as file:
    print(file.read())

OUTPUT

b'This   textample'

remember new bytes over write previous bytes



来源:https://stackoverflow.com/questions/4388201/how-to-seek-and-append-to-a-binary-file-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!