1

My original idea is to write a python version of this MATLAB function cmp2pal. I want to use python's colormap and transform it into pal files which can be used in origin and I don't want to open my matlab. The function's most important part is the following:

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

I searched for the solution but I still don't understand how the char or string can be saved as binary format (unsigned integer with precision). Can anyone give me the correct python version of this function? I used the struct module but there are errors:

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


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

the error message

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

error: required argument is not an integer
1
  • 1
    what is in newFileBytes ? And why do you use * ?
    – furas
    Jul 24, 2021 at 5:01

1 Answer 1

1

You have string

newFileBytes = 'RIFF'

but you need bytes

newFileBytes = b'RIFF'

And then it will work

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

But if you have bytes then you can write it directly to file

newFile.write(b'RIFF')

If you want to keep it as string then use encode to get bytes

newFileBytes = 'RIFF'.encode()

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.