Python-读取具有偏移量和结构的二进制文件

Python-读取具有偏移量和结构的二进制文件,python,struct,binaryfiles,binary-data,Python,Struct,Binaryfiles,Binary Data,我最近重新开始编程,并决定作为一个项目来推动我的工作,我打算为《辐射2》编写一个角色编辑器。我遇到的问题是,在前几个字符串之后,我似乎无法使用文件偏移量或结构提取所需的数据 这就是我正在做的。 我使用的文件是www.retro-gaming-world.com/SAVE.DAT import struct savefile = open('SAVE.DAT', 'rb') try: test = savefile.read() finally: savefile.

我最近重新开始编程,并决定作为一个项目来推动我的工作,我打算为《辐射2》编写一个角色编辑器。我遇到的问题是,在前几个字符串之后,我似乎无法使用文件偏移量或结构提取所需的数据

这就是我正在做的。 我使用的文件是www.retro-gaming-world.com/SAVE.DAT

import struct
savefile = open('SAVE.DAT', 'rb')
try:
        test = savefile.read()
finally:
        savefile.close()

print 'Header: ' +  test[0x00:0x18] # returns the save files header description "'FALLOUT SAVE FILE '"
print "Character Name: " + test[0x1D:0x20+4] Returns the characters name "f1nk"
print "Save game name: " + test[0x3D:0x1E+4] # isn't returning the save name "church" like expected
print "Experience: " + str(struct.unpack('>h', test[0x08:0x04])[0]) # is expected to return the current experience but gives the follosing error
输出:

Header: FALLOUT SAVE FILE
Character Name: f1nk
Save game name: 
    Traceback (most recent call last):
        File "test", line 11, in <module>
        print "Experience: " + str(struct.unpack('>h', test[0x08:0x04])[0])
    struct.error: unpack requires a string argument of length 2
我已经确认了偏移量,但它没有返回预期的任何内容。

test[0x08:0x04]是一个空字符串,因为结束索引小于开始索引

例如,test[0x08:0x0A]将根据h代码的要求提供两个字节


字符串切片的语法是s[start:end]或s[start:end:step]

按照我的理解,这是测试[offset:bytestoread],我对它的测试[offsetstart:offsetend]感到生疏了?谢谢你指出我搞乱了我的切片。test[0x08:0x08+20]谢谢。@user2806298请记住,结束索引不是结果的一部分,因此s[8:12]包括s[8]、s[9]、s[10]、s[11],但不包括s[12]。考虑这一点的另一种方式是s[start:start+length],对于步骤为1的常见情况。