简体   繁体   English

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

[英]Python - Reading binary file with offsets and structs

I've recently gotten back into programming and decided as a project to get me going and motivated I was going to write a character editor for fallout 2. The issue I'm having is after the first few strings I can't seem to pull the data I need using the file offsets or structs. 我最近回到编程领域,并决定作为一个项目来推动我前进,并有动力要编写辐射2的角色编辑器。我遇到的问题是在我似乎无法拉开的前几个字符串之后我需要使用文件偏移量或结构的数据。

This is what I am doing. 这就是我在做什么。 The file I Am working with is www.retro-gaming-world.com/SAVE.DAT 我正在使用的文件是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

output : 输出:

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

I've confirmed the offsets but it just isn't returning anything as it is expected. 我已经确认了偏移量,但是它没有返回预期的任何东西。

test[0x08:0x04] is an empty string because the end index is smaller than the starting index. test[0x08:0x04]是一个空字符串,因为结束索引小于开始索引。

For example, test[0x08:0x0A] would give you two bytes as required by the h code. 例如, test[0x08:0x0A]将根据h代码的要求为您提供两个字节。

The syntax for string slicing is s[start:end] or s[start:end:step] . 字符串切片的语法为s[start:end]s[start:end:step] Link to docs 链接到文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM