I manged to solve the problem. don't read the data manualy from the stream by "textSec.stream.read" use "textSec.data()" instead. Internaly (see "sections.py") a seek operation in the file is done. Afterwards the data is read. The result will be the valid data chunk. The following code reads the code(text) section of a atxmega firmware and copies it into a bytearray which has the layout of the flash of an atxmega128a4u device. @vlas_tepesch: the hex conversation is not needed and the the 64k pitfall is avoided.

sys.path[0:0] = ['.', '..']

from elftools.common.py3compat import bytes2str
from elftools.elf.elffile import ELFFile

# 128k flash for the ATXmega128a4u
flashsize = 128 * 1024


def __printSectionInfo (s):
    print ('[{nr}] {name} {type} {addr} {offs} {size}'.format(
                nr = s.header['sh_name'],
                name = s.name,
                type = s.header['sh_type'],
                addr = s.header['sh_addr'],
                offs = s.header['sh_offset'],
                size = s.header['sh_size']
                                                              )
           )

def process_file(filename):
    print('In file: ' + filename)
    with open(filename, 'rb') as f:
        # get the data
        elffile = ELFFile(f)
        print ('sections:')
        for s in elffile.iter_sections():
            __printSectionInfo(s)
        print ('get the code from the .text section')
        textSec = elffile.get_section_by_name(b'.text')
        # prepare the memory
        flashMemory = bytearray(flashsize)
        # the text section
        startAddr = textSec.header['sh_addr']
        val = textSec.data()

        flashMemory[startAddr:startAddr+len(val)] = val

        # print memory

        print('finished')

if __name__ == '__main__':
    process_file('firmware.elf')

Tanks for the comments!

Answer from Stefan Jaritz on Stack Overflow
🌐
GitHub
github.com › eliben › pyelftools
GitHub - eliben/pyelftools: Parsing ELF and DWARF in Python · GitHub
pyelftools is a regular Python library: you import and invoke it from your own code. For a detailed usage guide and links to examples, please consult the user's guide.
Starred by 2.3K users
Forked by 543 users
Languages   Python 97.7% | C 1.5% | Assembly 0.5% | Linker Script 0.1% | Makefile 0.1% | Nix 0.1%
🌐
PyPI
pypi.org › project › pyelftools
pyelftools · PyPI
Details for the file pyelftools-0.33-py3-none-any.whl.
      » pip install pyelftools
    
Published   May 29, 2026
Version   0.33
🌐
Medium
medium.com › analytics-vidhya › exploring-elf-files-using-pyelftools-93bb7665cce3
Exploring ELF files using pyelftools | by Roman Storozhenko | Analytics Vidhya | Medium
October 27, 2020 - pyelftools is a very flexible and convenient tool for observation of ELF binaries. It’s scope is far beyond simple examples given in this article and allow to create full-fledged exploring tools.
🌐
GitHub
github.com › eliben › pyelftools › blob › main › examples › dwarf_decode_address.py
pyelftools/examples/dwarf_decode_address.py at main · eliben/pyelftools
# elftools example: dwarf_decode_address.py · # # Decode an address in an ELF file to find out which function it belongs to · # and from which filename/line it comes in the original source file. # # Eli Bendersky (eliben@gmail.com) # This code is in the public domain · #------------------------------------------------------------------------------- import sys · · # If pyelftools is not installed, the example can also run from the root or ·
Author   eliben
Top answer
1 of 1
2

I manged to solve the problem. don't read the data manualy from the stream by "textSec.stream.read" use "textSec.data()" instead. Internaly (see "sections.py") a seek operation in the file is done. Afterwards the data is read. The result will be the valid data chunk. The following code reads the code(text) section of a atxmega firmware and copies it into a bytearray which has the layout of the flash of an atxmega128a4u device. @vlas_tepesch: the hex conversation is not needed and the the 64k pitfall is avoided.

sys.path[0:0] = ['.', '..']

from elftools.common.py3compat import bytes2str
from elftools.elf.elffile import ELFFile

# 128k flash for the ATXmega128a4u
flashsize = 128 * 1024


def __printSectionInfo (s):
    print ('[{nr}] {name} {type} {addr} {offs} {size}'.format(
                nr = s.header['sh_name'],
                name = s.name,
                type = s.header['sh_type'],
                addr = s.header['sh_addr'],
                offs = s.header['sh_offset'],
                size = s.header['sh_size']
                                                              )
           )

def process_file(filename):
    print('In file: ' + filename)
    with open(filename, 'rb') as f:
        # get the data
        elffile = ELFFile(f)
        print ('sections:')
        for s in elffile.iter_sections():
            __printSectionInfo(s)
        print ('get the code from the .text section')
        textSec = elffile.get_section_by_name(b'.text')
        # prepare the memory
        flashMemory = bytearray(flashsize)
        # the text section
        startAddr = textSec.header['sh_addr']
        val = textSec.data()

        flashMemory[startAddr:startAddr+len(val)] = val

        # print memory

        print('finished')

if __name__ == '__main__':
    process_file('firmware.elf')

Tanks for the comments!

🌐
DEV Community
dev.to › icyphox › python-for-reverse-engineering-1-elf-binaries-1fo4
Python for Reverse Engineering #1: ELF Binaries - DEV Community
March 14, 2019 - where capstone is the disassembly engine we’ll be scripting with and pyelftools to help parse ELF files. With that out of the way, let’s start with an example of a basic reversing challenge.
🌐
Eli Bendersky
eli.thegreenplace.net › 2012 › 01 › 06 › pyelftools-python-library-for-parsing-elf-and-dwarf
pyelftools - Python library for parsing ELF and DWARF - Eli Bendersky's website
January 6, 2012 - As a proof of capability, pyelftools ships with a fairly powerful clone of readelf. ... Website - managed as an open-source project on Github. It's the place for documentation, opening issues and closely following the development in general. Downloading - from PyPI, or the Github site. Documentation - there's a detailed user guide, and the source distribution contains several examples...
🌐
Readthedocs
instrumentation-infra.readthedocs.io › en › master › _modules › infra › packages › pyelftools.html
infra.packages.pyelftools — instrumentation-infra documentation
[docs]class PyElfTools(Package): """ :identifier: pyelftools-<version> :param version: version to download :param python_version: which Python version to install the package for """ def __init__(self, version: str, python_version: str): self.version = version self.python = Python(python_version) ...
Find elsewhere
🌐
GitHub
github.com › deepin-community › python-pyelftools
GitHub - deepin-community/python-pyelftools · GitHub
pyelftools is a regular Python library: you import and invoke it from your own code. For a detailed usage guide and links to examples, please consult the user's guide.
Author   deepin-community
🌐
GitHub
github.com › eliben › pyelftools › blob › main › doc › user-guide.md
pyelftools/doc/user-guide.md at main · eliben/pyelftools
May 29, 2026 - A variety of useful scripts and tools can be built on-top of the elftools library. As an example, one such script packaged with pyelftools is scripts/readelf.py, which is a (fairly faithful) clone of the readelf program from GNU binutils.
Author   eliben
Top answer
1 of 1
7

According to the author @eli-bendersky, pyelftools is a module for parsing and analyzing ELF/DWARF files and it has no direct way of modifying them. I had a look at the module source files and could not find any methods to edit/save either.

On the introductory post, within comments author acknowledges that pyelftools has no API-level support to do this but some tinkering around can help achieve what you need.

If pyelftools is not a hard dependency, here's an example on how to do the same using elffile:

Copyimport elffile

eo = elffile.open(name="/bin/ls")
eo.fileHeader.shnum = 30
with open('./ls.bin', 'wb') as f: f.write(eo.pack())

Using readelf, you can verify that changes were saved correctly:

Copyreadelf -h ls.bin 
ELF Header:
  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 
  Class:                             ELF32
  Data:                              2's complement, little endian
  Version:                           1 (current)
  OS/ABI:                            UNIX - System V
  ABI Version:                       0
  Type:                              EXEC (Executable file)
  Machine:                           Intel 80386
  Version:                           0x1
  Entry point address:               0x804be34
  Start of program headers:          105068 (bytes into file)
  Start of section headers:          103948 (bytes into file)
  Flags:                             0x0
  Size of this header:               52 (bytes)
  Size of program headers:           32 (bytes)
  Number of program headers:         9
  Size of section headers:           40 (bytes)
  Number of section headers:         30
  Section header string table index: 27
readelf: Error: Unable to read in 0x708 bytes of section headers

There's not much documentation on elffile but you can have a look at the source and figure out ways to replicate pyelftools-specific functionality. If that doesn't work, you can try using both pyelftools for reading/analyzing tasks and elffile to edit sections and write changes.

🌐
Debian
packages.debian.org › sid › python3-pyelftools
Debian -- Details of package python3-pyelftools in sid
pyelftools is a pure-Python library for parsing and analyzing ELF files and DWARF debugging information.
🌐
Stack Overflow
stackoverflow.com › questions › tagged › pyelftools
Newest 'pyelftools' Questions - Stack Overflow
This can be done from the terminal by running: readelf -l <elf_file>... ... I am trying to speed up how long it takes me to process a file in python. My idea is to split the task into n threads.
🌐
FreshPorts
freshports.org › devel › py-pyelftools
FreshPorts -- devel/py-pyelftools: Library for analyzing ELF files and DWARF debugging information
pyelftools is a pure-Python library for parsing and analyzing ELF files and DWARF debugging information
🌐
GitHub
github.com › eliben › pyelftools › issues › 227
Simple example for reading content of static variables · Issue #227 · eliben/pyelftools
May 10, 2019 - For example I have a static uint32_t timestamp = 0x1234; in my code, how can I read out the address and the initial value of that variable?
Author   eliben
🌐
Anaconda.org
anaconda.org › conda-forge › pyelftools
pyelftools - conda-forge | Anaconda.org
May 29, 2026 - conda-forge/pyelftools · Community · Library for analyzing ELF files and DWARF debugging information · Copied fromcf-post-staging / pyelftools · Overview · Files 198 · Labels 3 · Badges · Versions · 0.33 · To install this package, run one of the following: $conda install conda-forge::pyelftools ·