如何阅读.bin文件?

时间:2009-11-08 11:59:35

标签: python file binary

我从RealFlow 4导出了.bin文件,现在需要能够在Python中读取它,才能成为导入器。这些文件如何工作?

3 个答案:

答案 0 :(得分:5)

你走了:

import struct

class Particle:
    """A single particle.  Attributes added in BinFile."""
    pass

class BinFile:
    """Parse and store the contents of a RealFlow .bin file."""
    def __init__(self, fname):
        self.bindata = open(fname, "rb").read()
        self.off = 0

        self.verify = self.peel("=i")[0]
        assert self.verify == 0xfabada
        self.name = self.string(250)

        (self.version, self.scale, self.fluid_type, self.simtime, self.frame_number,
         self.fps, self.num_particles, self.radius) = self.peel("=hfifiiif")
        self.pressure = self.peel("=fff")
        self.speed = self.peel("=fff")
        self.temperature = self.peel("=fff")
        if self.version >= 7:
            self.emitter_position = self.peel("=fff")
            self.emitter_rotation = self.peel("=fff")
            self.emitter_scale = self.peel("=fff")

        self.particles = [self.peel_particle() for i in range(self.num_particles)]

    def peel_particle(self):
        """Read one particle from the file."""
        p = Particle()
        p.position = self.peel("=fff")
        p.velocity = self.peel("=fff")
        p.force = self.peel("=fff")
        if self.version >= 9:
            p.vorticity = self.peel("=fff")
        if self.version >= 3:
            p.normal = self.peel("=fff")
        if self.version >= 4:
            p.neighbors = self.peel("=i")[0]
        if self.version >= 5:
            p.texture = self.peel("=fff")
            p.infobits = self.peel("=h")[0]
        (p.age, p.isolation_time, p.viscosity, p.density, p.pressure, p.mass,
         p.temperature, p.id) = self.peel("=fffffffi")
        print p.id, p.neighbors, p.position
        return p

    def peel(self, fmt):
        """Read some struct data from `self.bindata`."""
        data = struct.unpack_from(fmt, self.bindata, self.off)
        self.off += struct.calcsize(fmt)
        return data

    def string(self, length):
        s = self.bindata[self.off:self.off+length].split("\0")[0]
        self.off += length
        return s

b = BinFile("Circle0100001.bin")
print "Name:", b.name
print "Particles:", b.num_particles
print "Position of first particle", b.particles[0].position

对样本数据运行时,会打印:

Name: Circle01
Particles: 1066
Position of first particle (-1.7062506675720215, 4.9283280372619629, -6.4365010261535645)

答案 1 :(得分:2)

您需要知道数据在文件中的编码方式。如果您有此信息,可以使用struct package将二进制数据转换为可在python中使用的内容。

我希望它有所帮助

答案 2 :(得分:0)

谢谢大家,我找到了这个文件。在这里我上传了它,并为你包含了一个粒子文件。

http://www.mediafire.com/download.php?xujqjghkcim