I would like to know how to easily read and write values from a Fortran namelist file in Python.
Asked
Active
Viewed 4,464 times
2 Answers
6
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

teekarna
- 1,004
- 1
- 10
- 13
-
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."* – Vladimir F Героям слава Jul 11 '18 at 14:38
-
1You 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. – Vladimir F Героям слава Jul 11 '18 at 14:39
-
1FWIW, 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` – Biggsy Jun 05 '19 at 15:05
-
Thanks @Biggsy, I've included pip installation instructions in the answer. – teekarna Jun 06 '19 at 08:09
3
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.

leifdenby
- 1,428
- 1
- 13
- 10