在 Python 中将类似 Fortran 的格式写入文件

Jia*_*eng 2 python fortran

在 Fortran 中,我可以使用:

open(10, file = 'output')
write(10, '(5A10)') 'apple', 'banana', 'orange', 'grape', 'berry'
Run Code Online (Sandbox Code Playgroud)

Python 中是否有类似的方式来编写输出?

我知道我可以使用:

f.write('%5s\t%5s\t%5s\t%5s\t%5s' % ('apple', 'banana', 'orange', 'grape', 'berry'))
Run Code Online (Sandbox Code Playgroud)

但怎样才能让它更紧凑呢?使用类似的方式'(5A10)',而不是冗长的'%5s\t%5s\t%5s\t%5s\t%5s'

小智 5

您可以使用 fortranformat: https://pypi.python.org/pypi/fortranformat

效果很好!

>>> import fortranformat as ff
>>> header_line = ff.FortranRecordWriter('(A15, A15, A15)')
>>> header_line.write(['x', 'y', 'z'])
  '              x              y              z'
>>> line = FortranRecordWriter('(3F15.3)')
>>> line.write([1.0, 0.0, 0.5])
  '          1.000          0.000          0.500'
>>> line.write([1.1, 0.1, 0.6])
  '          1.100          0.100          0.600'
Run Code Online (Sandbox Code Playgroud)