如何使用python将字符和整数写入具有特定精度的二进制文件?

问题描述

我最初的想法是编写这个 MATLAB 函数 cmp2pal 的 Python 版本。我想使用python的颜色图并将其转换为可以在原点使用的pal文件,我不想打开我的matlab。该函数最重要的部分如下:

    %% Open file
    fid=fopen(path,'w',mf);
    if(fid<0)
        throw(MException('cmap2pal:Open','Error opening file (%s) for writing',path));
    end

    %% Write RIFF signature
    fwrite(fid,'RIFF','uint8',mf);
    
    %% Write file length
    fwrite(fid,flen-8,'uint32',mf);                               % 8 byte header (RIFF header)
    
    %% Write PAL signature
    fwrite(fid,'PAL ',mf);
    
    %% Write data signature
    fwrite(fid,'data',mf);
    
    %% Write data block size
    fwrite(fid,flen-20,mf);                              % 20 byte header (RIFF + Chunk)
    
    %% Write version number
    fwrite(fid,[0,3],mf);                                 % Always 3
    
    %% Write palette length
    fwrite(fid,depth,'uint16',mf);
    
    %% Write palette data
    fwrite(fid,[cmap.*255,zeros(depth,1)]',mf);           % RGBA tuples
    
    %% Close file
    fclose(fid);

搜索解决方案,但我仍然不明白如何将字符或字符串保存为二进制格式(具有精度的无符号整数)。谁能给我这个函数的正确 python 版本?我使用了 struct 模块,但有错误

# %%
import struct
newFileBytes = 'RIFF'
# make file
newFile = open("testpython.txt","wb")
# write to file
# newFile.write(newFileBytes)


newFile.write(struct.pack('4B',*newFileBytes))
# %%

错误信息

----> 10 newFile.write(struct.pack('4B',*newFileBytes))

error: required argument is not an integer

解决方法

你有字符串

newFileBytes = 'RIFF'

但你需要字节

newFileBytes = b'RIFF'

然后它会起作用

struct.pack('4B',*newFileBytes)

但是如果你有字节,那么你可以直接将它写入文件

newFile.write(b'RIFF')

如果您想将其保留为字符串,请使用 encode 获取 bytes

newFileBytes = 'RIFF'.encode()

newFile.write( 'RIFF'.encode() )