使用Python导出基于二进制的文件



我目前正在为Blender编写导出脚本,但我觉得我的问题更多地是基于Python,所以我把它发布在了这里。

一位朋友用java为.obj文件创建了一个转换程序,将它们转换为自定义的二进制文件格式。然而,我想跳过这个过程,直接从Blender导出二进制文件。

该文件包含文本、整数和浮点,使用utf-8、utf-16和utf-32格式。

到目前为止,我已经将所有数据导出为标准文本文件,所以我只需要以适当的编码/格式输出它。以下是他在Java中使用的代码,用于以不同的编码将数据写入文件:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class StreamConverter {
//---------------------------------------------------
public static void buffer_write_string(DataOutputStream out,String text) throws IOException{
    byte[] bytes = text.getBytes();
    for(int i =0;i<text.length();i++){
        buffer_write_u8(out,bytes[i]);
    }
}
public static void buffer_write_u32(DataOutputStream out,int i) throws IOException{
    ByteBuffer b = ByteBuffer.allocate(4);
    b.order(ByteOrder.LITTLE_ENDIAN); 
    b.putInt(i);
    out.write(b.array());       
}
public static void buffer_write_u16(DataOutputStream out,int i) throws IOException{
    out.write((byte) i);
    out.write((byte) (i >> 8));     
}
public static void buffer_write_s16(DataOutputStream out,int i) throws IOException{
    out.write((byte) i);
    out.write((byte) (i >> 8));     
}
public static void buffer_write_s32(DataOutputStream out,int i) throws IOException{
    ByteBuffer b = ByteBuffer.allocate(4);
    b.order(ByteOrder.LITTLE_ENDIAN); 
    b.putInt(i);
    out.write(b.array());
}
public static void buffer_write_u8(DataOutputStream out,int i) throws IOException{
    out.writeByte((byte) i);
}
public static void buffer_write_s8(DataOutputStream out,int i) throws IOException{
    out.writeByte((byte) i);
}
public static void buffer_write_f64(DataOutputStream out,double i) throws IOException{
    ByteBuffer b = ByteBuffer.allocate(8);
    b.order(ByteOrder.LITTLE_ENDIAN); 
    b.putDouble(i);
    out.write(b.array());
}
public static void buffer_write_f32(DataOutputStream out,float i) throws IOException{
    ByteBuffer b = ByteBuffer.allocate(4);
    b.order(ByteOrder.LITTLE_ENDIAN); 
    b.putFloat(i);
    out.write(b.array());
}
}

我不确定如何使用Python来实现这一点,我正在尝试这样做,看看我是否至少可以正确地输出整数,但运气不好。

def write_u8(file, num):
    enum = num.encode('utf-8')
    file.write(enum)
def write_u16(file, num):
    enum = num.encode('utf-16')
    file.write(enum)
def write_u32(file, num):
    enum = num.encode('utf-32')
    file.write(enum)

示例用法:

write_u32(file, u'%i' % (vertex_count))

也尝试过这个:

counts = bytes([vertex_count,tex_count,normal_count])
file.write(counts)

我对整个二进制/编码有点迷失了方向,我已经通读了Python文档,但这并没有帮助。

任何教程或示例的链接都会很棒!

据我所知,您想做的是序列化对象并反序列化它。在Python中,Pickle是您要查找的包。你可以在这里查看它的文档。

最新更新