Python - 将文件写入给定的偏移量
Python - writing to file to a given offset
我有一个二进制文件名 binary_dump 看起来像这样
xxd binary_dump
0000000: 0000 4865 6c6c 6f20 776f 726c 6421 0000 ..Hello world!..
0000010: 726c 6421 726c 6421 rld!rld!
我的 objective 有一个给定的偏移量来写让我们说 /00/00/00/00
而不是字符串当前在给定的偏移量
我正在使用 python,这是我的代码
file = open('binary_dump', "w")
file.seek(2)
data= "[=12=][=12=][=12=][=12=]"
file.write(data)
file.close()
我得到的是:
xxd binary_dump
0000000: 0000 0000 0000 ......
有什么想法吗?
阅读文档中的打开模式。您想要的模式很可能是 "r+b"
,而不是 "w"
- 它不会截断文件。
您正在使用 w
模式截断文件,而不是以二进制模式打开它(如果您使用 Windows)。将模式从 w
更改为 r+b
:
file = open('binary_dump', "r+b")
有关详细信息,请参阅 Python 关于 Input and Output 的文档:
'w' for only writing (an existing file with the same name will be erased) [...]. 'r+' opens the file for both reading and writing.
我有一个二进制文件名 binary_dump 看起来像这样
xxd binary_dump
0000000: 0000 4865 6c6c 6f20 776f 726c 6421 0000 ..Hello world!..
0000010: 726c 6421 726c 6421 rld!rld!
我的 objective 有一个给定的偏移量来写让我们说 /00/00/00/00
而不是字符串当前在给定的偏移量
我正在使用 python,这是我的代码
file = open('binary_dump', "w")
file.seek(2)
data= "[=12=][=12=][=12=][=12=]"
file.write(data)
file.close()
我得到的是:
xxd binary_dump
0000000: 0000 0000 0000 ......
有什么想法吗?
阅读文档中的打开模式。您想要的模式很可能是 "r+b"
,而不是 "w"
- 它不会截断文件。
您正在使用 w
模式截断文件,而不是以二进制模式打开它(如果您使用 Windows)。将模式从 w
更改为 r+b
:
file = open('binary_dump', "r+b")
有关详细信息,请参阅 Python 关于 Input and Output 的文档:
'w' for only writing (an existing file with the same name will be erased) [...]. 'r+' opens the file for both reading and writing.