I would like to know how to easily read and write values from a Fortran namelist file in Python.
How to read/write a Fortran namelist with Python?
Asked Answered
There is a module called f90nml which reads/writes Fortran namelists. With this module you can read a namelist into a nested Python dictionary:
import f90nml
nml = f90nml.read('sample.nml')
The values can be edited and written back to disk.
nml['config_nml']['steps'] = 432
nml.write('new_sample.nml')
The package can be installed with pip
:
pip install f90nml
Source code is at https://github.com/marshallward/f90nml
Actually, there is already a deleted and downvoted answer here (you can't see it) which supplies this link. It was deleted with this comment: "While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes." –
Mamba
You do provide some more information in "which reads/writes Fortran namelists to/from a Python dictionary" but if you could add more, it would be safer for the answer's fate. –
Mamba
FWIW, I checked out both namelist_python and f90nml and I found that f90nml was better documented. Note also that both can be installed via pip, e.g.
pip install f90nml
–
Hanshaw Thanks @Biggsy, I've included pip installation instructions in the answer. –
Kuching
I wrote a python module to read/write Fortran namelist files because I couldn't find anything that quite worked for me: https://github.com/leifdenby/namelist_python
It:
- Parses ints, floats, booleans, escaped strings and complex numbers.
- Parses arrays in both index notation and inlined.
- Can write namelist format files.
- Has tab-completion and variable assignment in interactive console
I've written quite a few tests too, if there are any namelist files that don't parse correctly let me know and I'll have a look.
© 2022 - 2024 — McMap. All rights reserved.