title: How to write char and integer into binary files with specificed precison using python?
body: <p>My original idea is to write a python version of this MATLAB function <a href="https://www.mathworks.com/matlabcentral/fileexchange/43114-cmap2pal-convert-matlab-colormap-to-binary-pal-format" rel="nofollow noreferrer">cmp2pal</a>. 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:</p>
  <pre class="lang-matlab prettyprint-override"><code>    %% Open file
      fid=fopen(path,'w',mf);
      if(fid&lt;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);
  </code></pre>
  <p>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:</p>
  <pre><code># %%
  import struct
  newFileBytes = 'RIFF'
  # make file
  newFile = open(&quot;testpython.txt&quot;, &quot;wb&quot;)
  # write to file
  # newFile.write(newFileBytes)
  
  
  newFile.write(struct.pack('4B', *newFileBytes))
  # %%
  </code></pre>
  <p>the error message</p>
  <pre class="lang-py prettyprint-override"><code>----&gt; 10 newFile.write(struct.pack('4B', *newFileBytes))
  
  error: required argument is not an integer
  </code></pre>