Clone wiki

py-fortranformat / Home

Py-FortranFormat Library

This library allows Python programs to read and write according to Fortran FORMAT statements.

It implements similar functionality to the Perl Fortran Format Package.

There is some degree of configuration possible through the config sub-module.

Reading

Using the FortranRecordReader is the best way to read input

from fortranformat import FortranRecordReader

header_line = FortranRecordReader('(A15, A15, A15)')
print header_line.read('              x              y              z')
# Outputs: ['              x', '              y', '              z']
line = FortranRecordReader('(3F15.3)')
print line.read('          1.000          0.000          0.500')
# Outputs: [1.0, 0.0, 0.5]
print line.read('          1.100          0.100          0.600')
# Outputs: [1.1, 0.1, 0.6]

Limitations

Since Fortran variables must be predeclared, some input is cannot be determined when using Python, i.e.

  • 'G' edit descriptor on input (could be text, numerical or logical)
  • 'A' edit decriptors on input with no width, (cannot determine from a pre-sized array)

As such, the widthless A edit descriptor will simply read the entire rest of the string. The G edit descriptor will try out a series of edit descriptors specified in config.G_INPUT_TRIAL_EDS until one fits.

Writing

The FortranRecordWriter class is the best way to write output,

header_line = FortranRecordWriter('(A15, A15, A15)')
print header_line.write(['x', 'y', 'z'])
# Outputs: '              x              y              z'
line = FortranRecordWriter('(3F15.3)')
print line.write([1.0, 0.0, 0.5])
# Outputs: '          1.000          0.000          0.500'
print line.write([1.1, 0.1, 0.6])
# Outputs: '          1.100          0.100          0.600'

Configuration

Some configuration is possible through the config sub-module. See the separate wiki page for details.

Updated