How to read/write a Fortran namelist with Python?
Asked Answered
C

2

5

I would like to know how to easily read and write values from a Fortran namelist file in Python.

Culbreth answered 6/6, 2013 at 9:37 Comment(0)
K
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

Kuching answered 11/7, 2018 at 14:30 Comment(4)
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 f90nmlHanshaw
Thanks @Biggsy, I've included pip installation instructions in the answer.Kuching
C
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.

Clay answered 7/5, 2014 at 10:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.