15

我在将数据附加到二进制文件时遇到问题。当我seek()到一个位置,然后write()在那个位置然后读取整个文件时,我发现数据没有写入我想要的位置。相反,我在所有其他数据/文本之后找到它。

我的代码

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

您可以看到seek不起作用。我该如何解决这个问题?还有其他方法可以实现这一目标吗?

谢谢

4

4 回答 4

32

在某些系统上,'ab'强制所有写入发生在文件末尾。你可能想要'r+b'.

于 2010-12-08T13:54:14.133 回答
5

r+b 应该如你所愿

于 2010-12-08T14:26:39.243 回答
2

省略 seek 命令。您已经打开了附加“a”的文件。

于 2010-12-08T13:56:04.877 回答
-1

注意:记住新字节覆盖以前的字节

根据 python 3 语法

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

输出

b'This   textample'

记住新字节覆盖以前的字节

于 2019-07-29T11:19:54.180 回答