title: Python: Deleting a section from a PE file
body: <p>I am working with PE binaries using Python and the pefile library. For reading information out of a binary and rewriting certain bytes, this library does it job really well. But now I want to delete a section from the file completely.</p>
  
  <p>How would I do that? The only code I found concerning this task is in the function <code>pop_back()</code> at <a href="http://goo.gl/YYl5Vb" rel="nofollow">http://goo.gl/YYl5Vb</a>. But this code only removes the last section while I need to be able to remove any section.</p>
  
  <p>I suppose, I could remove the raw section data with something like</p>
  
  <pre><code>dead_sect_start = dead_sect.PointerToRawData
  dead_sect_ed = dead_sect.PointerToRawData + dead_sect.SizeOfRawData
  pe.__data__ = pe.__data__[:dead_sect_start] + pe.__data__[dead_sect_end:])
  </code></pre>
  
  <p>where pe is my parsed binary and dead_sect the section I want to remove.</p>
  
  <p>But then, how do I fix the section headers? I don't think I would get it right if I started to mangle with the single header bytes on my own. Isn't there some support for this in the pefile library? Or some code, someone more competent than me wrote?</p>
  
  <p>Thanks in advance!</p>